【问题标题】:Send Nested JSON from view to model将嵌套 JSON 从视图发送到模型
【发布时间】:2016-12-13 05:54:32
【问题描述】:

我想将嵌套 JSON 从视图发送到模型,还有其他关于此问题的问题,但它们的对象中都没有变量键。

JSON 对象:

"Login": {
    "userId": "harshal.bulsara",
    "userName": "Harshal Bulsara",
 },


"ListOfEntities": {
       "Patient": {
            0: "Add",
            1: "Edit"
          },
       "Practice": {
            0: "Add",
            1: "Edit",
            2: "List"
         },
   }

我能够正确发送带有密钥登录的数据,但我无法发送 ListOfEntities,这里重要的是这个 JSON 中的密钥每次都不相同(患者,练习)它可能会有所不同

这是型号代码:

public class authoritiesInfo
{
    public Dictionary<string, Dictionary<int,string>> ListOfEntities { get; set; }
}
public class dashboardModel
{
    public string userId { get; set; }
    public string userName { get; set; }

    public List<authoritiesInfo> auth { get; set; }
    public void createSession()
    {
        processing //
    }

}

这是控制器代码:

public class DashboardController : Controller
{
    // GET: Dashboard
    [HttpPost]
    public ActionResult Index(dashboardModel dm)
    {
        dm.createSession();
        return View();
    }
}

查看代码:

 var dt = [];
        dt.push({
            "userId": indexValue.value,
            "userName": $("#cmbName option:selected").text(),
            "auth": MY JSON mention above
        });


        $.ajax({
            type: "POST",
            url: '@Url.Action("Index", "Dashboard")',
            data: dt[0],
            crossDomain: true,
            success: function (data) {
               window.location.href = '@Url.Action("Page", "Dashboard")';
            },
            error: function (jqXHR, textStatus, error) {
                alert("Error");
            }
        });

问题:如何将嵌套 JSON 发送到控制器,JSON 来自 REST 服务,我也可以控制是否有其他解决方案需要任何修改,也欢迎

【问题讨论】:

  • 这甚至不是有效的 JSON :)
  • @StephenMuecke,你认为我需要完全更改 JSON 吗?
  • 是的。但它不清楚你试图绑定到什么。您是说您可以拥有一个包含诸如“Patient”、“Practice”和其他“键”之类的值的集合,并且每个集合都包含一个诸如“Add”、“Edit”等值的集合?使用 ajax 发布数据然后在回调中重定向也是没有意义的
  • 是的,有患者等值的集合,练习列表可以更改,如果您对发布数据有其他想法,我可以更改实现
  • 只是意味着将您的模型更改为 public class authoritiesInfo { public string Name { get; set; } public List&lt;string&gt; Values { get; set; } } 然后它将是 data: JSON.stringify({ userId: xxx, userName: xxx, auth: [{ Name: "Patient", Values: ["Add", "Edit"] }, { Name: "Practice", Values: [....] } ]}), 并设置 contentType: 'json' 选项。但是auth 的这些值是从哪里来的。如果它们来自表单控件,那么只需正确生成视图并使用$('form').serialize()

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


【解决方案1】:

为了绑定到 JSON,您必须设置 contentType: 'application/json' ajax 选项并使用 JSON.stringify() 对数据进行字符串化。

但是,JavaScriptSerializer 不会绑定嵌套字典,因此您将更改模型以接受嵌套列表

public class authoritiesInfo
{
    public string Name { get; set; }
    public List<string> Values { get; set; }
}
public class dashboardModel
{
    public string userId { get; set; }
    public string userName { get; set; }
    public List<authoritiesInfo> auth { get; set; }
}

然后数据将是

var data = {
    userId: 'harshal.bulsara',
    userName: 'Harshal Bulsara',
    auth: [
        {
            Name: 'Patient',
            Values: [ 'Add', 'Edit' ]
        },
        {
            Name: 'Practice',
            Values: ['Add', 'Edit', 'List']
        }
    ]
};

和ajax

$.ajax({
    url: '@Url.Action("Index", "Dashboard")',
    contentType: 'application/json',
    data: JSON.stringify({ dm: data }),
    type: 'POST',
    success: function (data) {
        ....
    }
});

然后绑定到

[HttpPost]
public ActionResult Index(dashboardModel dm)

旁注:如果您需要诸如[{ 0: 'Add' },{ 1, 'Edit' }] 之类的对象集合而不是字符串集合[ 'Add', 'Edit' ],则创建一个具有int IDstring Name 属性的附加类(例如Item),然后更改public List&lt;string&gt; Values { get; set; }public List&lt;Item&gt; Values { get; set; } 并将数据更改为

Name: 'Patient',
Values: [
    { ID: 2, Name: 'Add' },
    { ID: 3, Name: 'Edit' },
]

【讨论】:

    猜你喜欢
    • 2014-07-31
    • 2017-04-10
    • 1970-01-01
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 2018-03-17
    • 2023-02-14
    • 1970-01-01
    相关资源
    最近更新 更多