如何使用Ajax将JavaScript数组传递给C#函数
本文关键字:函数 数组 何使用 Ajax JavaScript | 更新日期: 2023-09-27 17:54:04
我有一个JavaScript中的字符串数组,点击按钮,点击这里的按钮,dataArray将表中第一个元素的字符串值存储为JSON,然后我将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内部服务器
在将JSON发送到WebMethod
之前,始终字符串化JSON
data: JSON.stringify({ Students: dataArr })
这将起作用(在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
}
通过List<string> data
尝试
[WebMethod]
public static void DeleteStudent(string[] data)
{
其他
[WebMethod]
public static void DeleteStudent(List<string> data)
{
data: { data : dataArr },