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

标签 c# ajax asp.net-mvc model

我正在尝试通过 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 中,您还必须指定应从 POST 请求正文中获取 m,方法是将您的端点标记为 HttpPost并用 FromBody 注释您的参数标签:

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

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

相关文章:

c# - Visual Studio 代码自动完成

javascript - 统计ajax返回数据中的html元素数量

javascript - 使用帖子 id 作为 id 属性来构建博客帖子

c# - Javascript 函数参数未显示在 Asp.Net MVC RouteValueDictionary 中?

用于格式化文本的 JavaScript 函数

c# - 单声道的响应式(Reactive)扩展?

c# - .NET Framework 4.5 及更高版本是否可用于 Embedded Compact 2013 和 Windows 10 IoT Core?

javascript - 在 URL 中发布多个变量并使用复选框

c# - MVC ActionLink 将路由附加为查询字符串而不是路由值

c# - 为什么我得到 'One or more types required to compile a dynamic expression cannot be found.' ?