gpt4 book ai didi

javascript - 如何将数组从 jQuery Ajax 传递到 MVC 5 Action ?

转载 作者:塔克拉玛干 更新时间:2023-11-02 22:34:20 25 4
gpt4 key购买 nike

我尝试通过 Ajax 将我的网格数据从 jQuery 传递到 MVC 操作。我的页面上有一个“保存”按钮,这是用于点击的 jQuery 代码:

var result = [];
$('#btnSave').click(function () {
$('#tblMatters tbody tr.mattersRow').each(function () {
var item = {};

if ($(this).find('td.qbmatter > div.dropdown').length > 0) {
item.QBMatter = $(this).find('td.qbmatter > div.dropdown > a').text();
} else {
item.QBMatter = $(this).find('td.qbmatter').text();
}

item.Hours = $(this).find('td.hours').text();
item.Person = $(this).find('td.person').text();

if ($(this).find('td.rate > div.dropdown').length > 0) {
item.Rate = $(this).find('td.rate > div.dropdown > a').text();
} else {
item.Rate = $(this).find('td.rate').text();
}

item.Amount = $(this).find('td.amount').text();
result.push(item);
});

$.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: { 'Matters': result },
dataType: "json",
traditional: true,
contentType: "application/json; charset=utf-8",
success: function (data) { alert("Success!"); },
error: function () { alert("An error has occured!!!"); }
});
});

我检查了 result 数组,它是正确的。它包含应有的每一个值。在我的 HomeController 中,我的数据有以下模型:

public class QBMatter
{
public string QBDescription { get; set; }
public string Person { get; set; }
public decimal Hours { get; set; }
public int Rate { get; set; }
public decimal Amount { get; set; }
}

以及以下操作:

public ActionResult SaveQBMatter (QBMatter[] Matters)
{
DBAccess dba = new DBAccess();
int QBMatterID = 0;
foreach (QBMatter qb in Matters)
{
dba.InsertQBMatter(qb.QBDescription, qb.Person, qb.Hours, qb.Rate, qb.Amount, ref QBMatterID);
}

return RedirectToAction("Home", "Index", "Home");
}

但我总是得到 “发生错误!!!” 结果...我什至没有采取行动,所以在 ajax 级别的某处出错...我做错了什么?

最佳答案

您需要在发送数据时将数据字符串化。

尝试:

             $.ajax({
url: "/Home/SaveQBMatter",
type: "POST",
data: JSON.stringify({ 'Matters': result }),
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function (data) {
alert("Success!");
},
error: function () {
alert("An error has occured!!!");
}
});

关于javascript - 如何将数组从 jQuery Ajax 传递到 MVC 5 Action ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20197556/

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