akr akr - 3 months ago 27
jQuery Question

How to pass a javascrpt array to C# function using Ajax

i have this array of strings in javascript passed on the button click here on button click the dataArr stores string value of first elements from the table in which some of the rows has been selected after that i stringify as JSON and call a ajax function to send the data to my code behind function DeleteStudent.

my javascript function that i call on button click:

$('#deleteStudent').click(function () {
var dataArr = [];
$.each($("#StudentTable tr.selected"), function () {
var StudentList = JSON.stringify(dataArr);
type: "POST",
url: "ViewStudents.aspx/DeleteStudent",
contentType: "application/json; charset=utf-8",
data: { Students: dataArr },
dataType: "json",
traditional: true,
success: function (result) {
alert('Yay! It worked!');
error: function (result) {
alert('Oh no :( : '+result);

the dataArr looks like ["10363","10364","10366"]

the code behind function:

public static void DeleteStudent(string[] Students)
Console.WriteLine("Reached CS");
string[] a =Students;
for (int i = 0; i < a.Length; i++)
string admissionNumber=a[i];
using (MySqlConnection conn = new MySqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString))
using (MySqlCommand deleteStudent = new MySqlCommand())
deleteStudent.CommandType = CommandType.Text;
deleteStudent.Connection = conn;
deleteStudent.CommandText = "DELETE FROM validstudents WHERE admissionNumber = @admissionNumber ";

deleteStudent.Parameters.AddWithValue("@admissionNumber", admissionNumber);


it gives a 500 internal server


Always stringify JSON before sending it to a WebMethod

data: JSON.stringify({ Students: dataArr })