在ASP.NET MVC 5控制器中接收json数据

时间:2018-09-01 04:18:44

标签: c# asp.net-mvc

检查下面显示的代码。我将一些json发布到控制器方法。我想在名为MenuItems的C#模型类中接收值;但问题是:我可以将数据发布到控制器,但是所有的“ MenuItems”都返回null。数据分配不正确。我该如何解决?

AJAX:

var obj = '[{ "text": "wewer", "target": "_self", "children": [{ "text": "wer", "target": "_top" }] }]';


$.ajax({
        type: "POST",
        url: "/Custom/SaveMenu",
        data: JSON.stringify(obj),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) { alert(data); },
        failure: function (errMsg) {
            alert(errMsg);
        }
    });

型号:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace DemoWeb.ViewModels
{
    public class MenuItems
    {
        public string text { get; set; }
        public string target { get; set; }
        public List<Child> children { get; set; }
    }

    public class Child
    {
        public string text { get; set; }
        public string target { get; set; }
    }
}

控制器:

[HttpPost]
public JsonResult SaveMenu(MenuItems menuItems)
{
    //'menuItems' this returns null for all properties

    //return Json("pokay");
}

1 个答案:

答案 0 :(得分:3)

您必须在[的首尾都删除]obj

因此obj从更改:

var obj = '[{ "text": "wewer", "target": "_self", "children": [{ "text": "wer", "target": "_top" }] }]';

对此:

var obj = '{ "text": "wewer", "target": "_self", "children": [{ "text": "wer", "target": "_top" }] }';

然后应用data: obj,然后删除data: JSON.stringify(obj),

完整代码:

var obj = '{ "text": "wewer", "target": "_self", "children": [{ "text": "wer", "target": "_top" }] }';


$.ajax({
        type: "POST",
        url: "/Custom/SaveMenu",
        data: obj,
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) { alert(data); },
        failure: function (errMsg) {
            alert(errMsg);
        }
    });