将复杂的JSON提交给MVC控制器。如何命名嵌套对象?

时间:2014-04-16 16:21:59

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

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

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

1 个答案:

答案 0 :(得分:7)

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

更改为编码JSON:

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