2

I have a complex JSON object that I'd like to pass to a MVC4 Controller route.

{
"name": "Test",
"description": "Description",
"questions": [
    {
        "id": "1",
        "type": "1",
        "text": "123",
        "answers": [
            {
                "answer": "123",
                "prerequisite": 0
            },
            {
                "answer": "123",
                "prerequisite": 0
            }
        ],
        "children": [
            {
                "id": "2",
                "type": "2",
                "text": "234",
                "answers": [
                    {
                        "answer": "234",
                        "prerequisite": 0
                    },
                    {
                        "answer": "234",
                        "prerequisite": 0
                    }
                ],
                "children": []
            }
        ]
    }
]

I have these ViewModels defined:

public class FormDataTransformContainer
{
    public string name { get; set; }
    public string description { get; set; }
    public QuestionDataTransformContainer[] questions;
}

public class QuestionDataTransformContainer {
    public int type { get; set; }
    public string text { get; set; }
    public AnswerDataTransformContainer[] answers { get; set; }
    public QuestionDataTransformContainer[] children { get; set; }
}

public class AnswerDataTransformContainer {
    public string answer { get; set; }
    public int prerequisite { get; set; }
}

And this is the route I'm hitting:

    [HttpPost]
    public ActionResult Create(FormDataTransformContainer formData)
    {

Currently, the name and description property on FormDataTransformContainer are set, but the questions array is null. I hoped that the Data Binding would figure it out, but I assume the tree nature of the data structure is a little complex for it. If I'm correct what is the best solution to this?

4

3 回答 3

3

questions应该是属性,而不是字段。我还将从数组更改为IList<>(假设您的序列化库处理得很好),因为这可能更接近它应该是什么,并允许您使用更通用的接口而不是特定的实现。

public class FormDataTransformContainer
{
  public string name { get; set; }
  public string description { get; set; }
  public IList<QuestionDataTransformContainer> questions { get; set; }
}

public class QuestionDataTransformContainer {
  public int type { get; set; }
  public string text { get; set; }
  public IList<AnswerDataTransformContainer> answers { get; set; }
  public IList<QuestionDataTransformContainer> children { get; set; }
}

public class AnswerDataTransformContainer {
  public string answer { get; set; }
  public int prerequisite { get; set; }
}

我已经用 Json.net(我相信 MVC4 的默认设置)测试了这个结构,并且它可以工作。

于 2013-09-23T20:21:38.617 回答
0

正如@robert-harvey 所说,您应该利用JSON.NET 之类的库来为您完成繁重的工作。

从 JSON.NET API 文档中提取:
如果您创建一个string json保存 json 的文件,则可以使用new JsonTextReader(new StringReader(json))

于 2013-09-23T20:10:01.700 回答
0

我有类似的问题,用以下代码解决:

public class ExtendedController : Controller
{
    public T TryCreateModelFromJson<T>(string requestFormKey)
    {
        if (!this.Request.Form.AllKeys.Contains(requestFormKey))
        {
            throw new ArgumentException("Request form doesn't contain provided key.");
        }

        return
            JsonConvert.DeserializeObject<T>(
                this.Request.Form[requestFormKey]);
    }
}

和用法:

    [HttpPost]
    [ActionName("EditAjax")]
    public ActionResult EditAjaxPOST()
    {
        try
        {
            var viewModel =
                this.TryCreateModelFromJson<MyModel>(
                    "viewModel");

            this.EditFromModel(viewModel);

            return
                this.JsonResponse(
                    this.T("Model updated successfuly."),
                    true);
        }
        catch (Exception ex)
        {
            this.Logger.Error(ex, "Error while updating model.");

            return this.JsonResponse(this.T("Error"), false);
        }
    }

从 JS 调用:

function saveViewModel() {
    $.post(
        '@Url.Action("EditAjax")',
        {
            __RequestVerificationToken: '@Html.AntiForgeryTokenValueOrchard()',
            viewModel: ko.mapping.toJSON(viewModel)
        },
        function (data) {
             // response
        });
}

用于反序列化/序列化 JSON 的附加库:http ://www.nuget.org/packages/Newtonsoft.Json

于 2013-09-23T20:29:35.430 回答