【问题标题】:Submitting complex JSON to MVC controller. How do I name nested objects?将复杂的 JSON 提交给 MVC 控制器。如何命名嵌套对象?
【发布时间】:2014-04-16 16:21:58
【问题描述】:

我设置了一个控制器,期望将此对象发布到它:

public class PrintJob
{
    public string BarTenderFile { get; set; }
    public string PrinterName { get; set; }
    public List<TagLabel> Queue { get; set; } 
}

public class TagLabel
{
    public string Season { get; set; }
    public string STSStyle { get; set; }
    public string VStyle { get; set; }
    public string ColorCode { get; set; }
    public int CODI { get; set; }
    public string SizeDesc { get; set; }
    public string StyleDesc { get; set; }
    public string ColorDesc { get; set; }
    public string Vendor { get; set; }
    public int Qty { get; set; }
    public long UPC { get; set; }
    public double CurrRetail { get; set; }
    public double OrigRetail { get; set; }
    public string AvailableIn { get; set; }
}

我正在尝试通过 AJAX 提交到我的控制器,使用 JSON 来表示我的对象。它适用于PrintJob 的顶级属性,控制器可以看到BarTenderFilePrinterName 属性的值。问题是Queue。我的 javascript 看起来像这样:

var queue = [];

$('#queue tr').each(function () {
    var tagLabel = $.parseJSON($(this).find('pre').text());
    queue.push(tagLabel);
});

var data = {
    "BarTenderFile": $('#btFile').val(),
    "PrinterName": $('#printer').val(),
    "Queue": queue
}

$.ajax({
    type: 'POST',
    url: window.submitQueueUrl,
    dataType: "application/json",
    data: data,
    success: function (returnVal) {
        // Do success stuff
    }
});

每个 Queue 对象的 JSON 存储在页面上隐藏的 &lt;pre&gt; 标记中,其格式使每个名称都与我的 TagLabel 对象中的名称匹配。我认为这比使用大量隐藏输入字段更容易。发送的 JSON 不会产生错误,后端代码会毫无问题地消化它。问题是当我将它提交给控制器时,Queueobject 的列表填充。最终结果是,在我的控制器中,Queue 将有我选择的许多队列项目,但每个队列项目都由空值和零填充。如何告诉我的控制器识别每个队列项是 TagLabel 而不是通用对象?

【问题讨论】:

  • 您没有发送 JSON,请将 data: 更改为 data: JSON.stringify(data),dataType 还指定了响应类型,而不是您发送的类型 (contentType)。
  • 数据看起来还不错,但是你能把tagLabel的样子发一下吗?
  • @MrCode /headdesk。当然就是这样。把它作为答案,我会标记它。谢谢!

标签: c# jquery ajax asp.net-mvc json


【解决方案1】:

扩展我的评论:数据没有被编码为 JSON。 jQuery 将尝试从对象构建正常的 URL 编码数据(这解释了为什么会收到第一部分)。

更改为 JSON 编码:

$.ajax({
    data: JSON.stringify(data),
    contentType : 'application/json' // also set the content type
    ...
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-06-28
    • 1970-01-01
    • 2020-04-23
    • 1970-01-01
    • 2014-10-20
    • 2011-09-05
    • 2014-02-28
    相关资源
    最近更新 更多