简体   繁体   English

AJAX POST复杂JSON到MVC4控制器

[英]AJAX POST Complex JSON to MVC4 Controller

I have a complex JSON object that I'd like to pass to a MVC4 Controller route. 我有一个复杂的JSON对象,我想传递给MVC4控制器路由。

{
"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: 我定义了以下ViewModel:

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. 当前,在FormDataTransformContainer上设置了名称和description属性,但是问题数组为空。 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? 如果我正确的话,什么是最好的解决方案?

questions should be a property, not a field. questions应该是属性,而不是字段。 I'd also change from arrays to IList<> (assuming your serialization library handles that well), because that's probably closer to what it should be, and lets you use a more generic interface instead of a specific implementation. 我也将从数组更改为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; }
}

I've tested this structure with Json.net (MVC4's default, I believe), and it works. 我已经使用Json.net(我相信MVC4的默认设置)测试了此结构,并且它可以工作。

As @robert-harvey said, you should utilize libraries like JSON.NET that are already available to do the heavy lifting for you. 正如@ robert-harvey所说,您应该利用JSON.NET之类的库来为您完成繁重的工作。

Pulled from the JSON.NET API docs: 从JSON.NET API文档中提取:
If you create a string json that holds your json, you can read from it with new JsonTextReader(new StringReader(json)) 如果创建包含您的json的string json ,则可以使用new JsonTextReader(new StringReader(json))从中进行读取

I a similar problem, solved with the following code: 我有一个类似的问题,用以下代码解决:

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]);
    }
}

And usage: 和用法:

    [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);
        }
    }

Called from JS: 从JS调用:

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

Used additional library for deserializing/serializing JSON: http://www.nuget.org/packages/Newtonsoft.Json 用于反序列化/序列化JSON的其他库: http : //www.nuget.org/packages/Newtonsoft.Json

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM