akr akr - 1 month ago 13x
C# Question

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

i have array of strings in JavaScript passed on the button click, here on button click the dataArray stores string value of first elements from the table in which some of the rows has been selected after that i

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 dataArray looks like this


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 })