akr akr - 1 year ago 170
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

Answer Source

Always stringify JSON before sending it to a WebMethod

data: JSON.stringify({ Students: dataArr })
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download