2016-07-03 85 views
1

我在JavaScript中傳遞了一個字符串數組,通過按鈕單擊,在這裏按鈕單擊dataArray存儲從其中某些行已被之後選擇我作爲JSON並調用Ajax函數將數據發送到函數DeleteStudent後面的代碼。
我的JavaScript函數,我請點擊鏈接:如何使用Ajax將JavaScript數組傳遞給C#函數

$('#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內部服務器

+0

集'傳統:真'在你的ajax請求選項中。 –

+0

不工作添加該行 – akr

回答

3

始終字符串化JSON這將工作(在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 
} 
+0

非常感謝:)正在使用stringify,但沒有將其發送到ajax函數 – akr

0

試用其發送到WebMethod

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

前10

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

其他

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

    data: { data : dataArr },