如何使用Ajax将JavaScript数组传递给C#函数

时间:2016-07-03 03:37:42

标签: javascript c# jquery asp.net ajax

我在按钮点击时传递了JavaScript中的字符串数组,这里按钮单击dataArray存储表格中第一个元素的字符串值,其中一些行被选中后{i} stringify为JSON并调用Ajax函数将数据发送到函数DeleteStudent后面的代码 我点击按钮时调用的JavaScript函数:

$('#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);
    });

dataArray看起来像这样

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

功能背后的代码:

[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();
            }
        }
    }
}

它提供了500个内部服务器

3 个答案:

答案 0 :(得分:4)

在将JSON发送到WebMethod

之前始终对其进行字符串化
data: JSON.stringify({ Students: dataArr })

答案 1 :(得分:1)

这将有效(在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
}

答案 2 :(得分:0)

尝试List<string> data

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

否则

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

   data: { data : dataArr },