我正在尝试通过 AJAX 将嵌套对象发送到我的 mvc Controller 。 我的数据集如下。
function GetValuesForSave() {
var model = {
Partycode: "x",
DocDate: new Date(),
DocNo: 1,
SaleItems: {
StockCode:'',
Amount: 1,
DiscPerc: 1,
DiscAmount: 1,
Qty: 1,
Rate: 1,
Description: '',
Unit: ''
}
}
return model;
}
我的 Ajax 调用:
var datatosend=GetValuesForSave();
$.ajax({
url: "/Sales/SaveSales/",
data: datatosend,
success: function() {
alert("success");
},
error: function() {
alert("failure");
}
});
我的模型结构:
public class SalesViewModel
{
public string Partycode { get; set; }
public DateTime DocDate { get; set; }
public int DocNo { get; set; }
private SaleItem _saleItem;
public SaleItem SaleItems { get; set; }
}
public class SaleItem
{
public string StockCode { get; set; }
public string Description { get; set; }
public string Unit { get; set; }
public double Qty { get; set; }
public double Rate { get; set; }
public double DiscPerc { get; set; }
public double DiscAmount { get; set; }
public double Amount { get; set; }
}
我的 Controller 方法:
public ActionResult SaveSales(SalesViewModel m)
{
var data = sale;
return View();
}
我面临的问题是我能够从 Controller 获取主要模型详细信息,但嵌套对象字段为空,我错过了一些东西。 我需要对嵌套属性的 GET SET 执行任何操作吗?我尝试将数据作为 JSON 字符串发送,但仍然得到相同的结果。
请查找 Chrome 控制台日志
最佳答案
您当前正在执行 GET 请求。因此,jQuery 的 ajax
方法尝试将 data
解释为查询字符串,这就是为什么您只能在 Controller 方法中获得“顶级”键值对。
为了使其正常工作,您需要将 ajax
调用修改为:
$.ajax({
type: "POST", // perform POST request
url: "/Sales/SaveSales/",
data: JSON.stringify(datatosend), // serialize your data into JSON
contentType: "application/json", // tell server to interpret data as JSOn
success: function() {
alert("success");
},
error: function() {
alert("failure");
}
});
在您的 Controller 中,您还必须指定应从 POST 请求正文中获取 m
,方法是将您的端点标记为 HttpPost
并用 FromBody
注释您的参数标签:
[HttpPost]
public ActionResult SaveSales([FromBody] SalesViewModel m)
{
// ...
}
关于c# - 嵌套对象不与服务器端模型映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56922399/