gpt4 book ai didi

c# - 嵌套对象未与服务器端模型映射

转载 作者:行者123 更新时间:2023-11-30 21:27:57 25 4
gpt4 key购买 nike

我正在尝试通过 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 字符串发送,但仍然得到相同的结果。 enter image description here

请找到 chrome 控制台日志

enter image description here

最佳答案

您当前正在执行 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 中,您还必须通过将端点标记为 HttpPost 来指定 m 应该从 POST 请求的正文中获取。并使用 FromBody 注释您的参数标签:

[HttpPost]
public ActionResult SaveSales([FromBody] SalesViewModel m)
{
// ...
}

关于c# - 嵌套对象未与服务器端模型映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56922399/

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