将json对象解析为asp.mvc 5中的viewmodel

时间:2014-07-17 08:03:16

标签: c# asp.net-mvc json asp.net-mvc-5

我有一个JSON对象:

{ "Questions": { "Id": "3a19f538-0cf6-e311-93f5-000c2948090b", "Question": "wedwe", "Answer": "4" }, "items": ["3a19f538-0cf6-e311-93f5-000c2948090b"]},

我正在尝试将其发送给MVC控制器操作:

    $.ajax({
    type: "POST",
    url: url,
    data: { "Questions": { "Id": "3a19f538-0cf6-e311-93f5-000c2948090b", "Question": "wedwe", "Answer": "4" }, "items": ["3a19f538-0cf6-e311-93f5-000c2948090b"]},
    dataType: 'json',
    traditional: true,
}).done(AprovingResponse);

但在我的行动中:

[POST]
public JsonResult AddFeedback(TestModel model)
{
    [...]
}

不是整个模型都填满了:

    public class TestModel
    {
        public List<Guid> items { get; set; }
        public List<ViewModelQuestion> Questions { get; set; }
    }

    public class ViewModelQuestion
    {
        public Guid Id { get; set; }
        public string Question { get; set; }
        public string Answer { get; set; }
    }

仅填写项目列表,问题列表包含0个元素

enter image description here

我找不到这个问题的根源。你能帮助我吗?

- 编辑 -

当我将json更改为mach对象集合时,没有差异:

data: { "Questions": [{ "Id": "3a19f538-0cf6-e311-93f5-000c2948090b", "Question": "wedwe", "Answer": "4" }, { "Id": "3a19f538-0cf6-e311-93f5-000c2948090b", "Question": "wedwe", "Answer": "4" }], "items": ["3a19f538-0cf6-e311-93f5-000c2948090b", "3a19f538-0cf6-e311-93f5-000c2948090b"] },

enter image description here

1 个答案:

答案 0 :(得分:2)

我认为您的JSON对象不适合某个类。我认为应该是:

{ "Questions": [{ "Id": "3a19f538-0cf6-e311-93f5-000c2948090b", "Question": "wedwe", "Answer": "4" }], "items": ["3a19f538-0cf6-e311-93f5-000c2948090b"]}

在您的JSON Questions属性中是单个JSON对象(字段 ID 问题答案),但在您的查看模型,你期待一组对象。