2016-07-03 8 views
1

JavaScriptの文字列の配列をボタンでクリックすると、ここでボタンがクリックされます。dataArrayは、行の一部があるテーブルの最初の要素の文字列値を格納します。それ以降JSONとしてi stringifyを選択し、Ajax関数を呼び出して、関数DeleteStudentの後ろにあるコードにデータを送信します。私は、ボタンの上に呼び出す
私のJavaScript関数をクリックしてください:JavaScript配列をAjaxを使用して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

not working that lines – akr

答えて

3

常に文字列化JSON WebMethod

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

ありがとうalot :) stringifyを使用していましたが、ajax関数に送信しませんでした – akr

0

試してみる他の10

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

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

    data: { data : dataArr }, 
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 
} 
関連する問題