最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How to pass a JavaScript array to C# function using Ajax - Stack Overflow

programmeradmin5浏览0评论

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 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 () {
                dataArr.push($(this).find('td').eq(0).text()); 
            });
            var StudentList = JSON.stringify(dataArr);
            $.ajax({
                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);
                }
            });
            console.log(StudentList);
    });

the dataArray looks like this

["10363","10364","10366"]

the code behind function:

[WebMethod]
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);

                conn.Open();
                deleteStudent.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
}

it gives a 500 internal server

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 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 () {
                dataArr.push($(this).find('td').eq(0).text()); 
            });
            var StudentList = JSON.stringify(dataArr);
            $.ajax({
                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);
                }
            });
            console.log(StudentList);
    });

the dataArray looks like this

["10363","10364","10366"]

the code behind function:

[WebMethod]
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);

                conn.Open();
                deleteStudent.ExecuteNonQuery();
                conn.Close();
            }
        }
    }
}

it gives a 500 internal server

Share Improve this question edited Aug 31, 2016 at 4:14 Jorawar Singh 7,6214 gold badges28 silver badges40 bronze badges asked Jul 3, 2016 at 3:37 aashishkraashishkr 551 silver badge8 bronze badges 2
  • Set traditional: true in your ajax request options. – AhmadReza Payan Commented Jul 3, 2016 at 4:20
  • not working added that line – aashishkr Commented Jul 3, 2016 at 4:32
Add a ment  | 

3 Answers 3

Reset to default 4

Always stringify JSON before sending it to a WebMethod

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

This will work(In javascript)

       var optionSelected ="me"
                    var id = { id: optionSelected };

                    $.ajax({
                        url: '@Url.Action("GetConnectionProvider", "Customers")',
                        contentType: "application/json;charset=utf-8",
                        data: JSON.stringify(id),
                        type: 'POST',
                        dataType: 'json',
                        success: function(datas) {


                        }
                    });
In Action

 public ActionResult GetConnectionProvider(int id)
{
   //write your code
}

Try by List<string> data

[WebMethod]
public static void DeleteStudent(string[] data)
{

else

 [WebMethod]
public static void DeleteStudent(List<string> data)
{   

   data: { data : dataArr },
发布评论

评论列表(0)

  1. 暂无评论