gpt4 book ai didi

c# - jquery 调用页面方法失败

转载 作者:行者123 更新时间:2023-12-01 08:28:46 25 4
gpt4 key购买 nike

我正在尝试使用 jquery 调用页面方法将数据从 HTML 表保存到数据库。但是,jquery 调用失败并显示:500 内部服务器错误。有什么建议吗?

下面是代码:

脚本:

    $(document).ready(function() {


$("#save").click(function(event) {

var i = 0;
var inputs = new Array();
$("#tbNames").find("input").each(function() {
inputs[i] = [this.id, this.value];
i++;
});

var columnsCount = 2;
$.ajax({

type: "POST",
url: "Default2.aspx/Save",
contentType: "application/json; charset=utf-8",
data: "{inputs: inputs, columnsCount: columnsCount}",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});
});
function AjaxSucceeded(result) {
alert(result.d);
}

function AjaxFailed(result) {
alert(result.status + ' ' + result.statusText);
}

});



</script>

HTML:

姓名 任务 删除

    <input id="save" type="button" value="Save data" />

页面方法的C#代码:

 [WebMethod ()]
public static List<Hashtable> ParseJson(string[] array, int rowsCount)
{
var result = new List<Hashtable>();

List<string[]> list = new List<string[]>();
foreach (var item in array)
{
int comma = item.IndexOf(',');
list.Add(new string[] { item.Substring(0, comma), item.Substring(comma + 1) });
}

int i = 0;
while (i < list.Count)
{
var dict = new Hashtable();
int j = i + rowsCount;
for (; i < j; i++)
{
dict.Add(list[i][0], list[i][1]);
}

result.Add(dict);
}

return result;

}

[WebMethod()]
public static string Save(string[] inputs, int columnsCount)
{
List<Hashtable> r = ParseJson(inputs, columnsCount);

List<TestClass> listOfTasks = new List<TestClass>();
foreach (var item in r)
{
TestClass tc = new TestClass();
tc.name = (string)item["name"];
tc.task = (string)item["task"];

listOfTasks.Add(tc);
}

DBManager dbm = new DBManager();
string actionResult = dbm.SaveData(listOfTasks);
if (actionResult == String.Empty)
{
return "Saved!";
}
else
{
return actionResult;
}
}

最佳答案

关键是json2.js及其stringify函数。实现该函数 AJAX 调用后看起来像这样:

$.ajax({ type: "POST",
url: "Default2.aspx/Save",
contentType: "application/json; charset=utf-8",
data: "{'inputs':" + JSON.stringify(inputs) + ",'columnsCount':1 }",
dataType: "json",
success: AjaxSucceeded,
error: AjaxFailed
});

source .

关于c# - jquery 调用页面方法失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1418037/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com