【问题标题】:[MVC3]Can't bind JSON array[MVC3]无法绑定 JSON 数组
【发布时间】:2012-09-04 12:30:33
【问题描述】:

我认为 MVC3 默认可以将 JSON 数据绑定到模型。

但是这段代码

服务器:

[HttpPost]
public ActionResult Save(IList<int> IDs)
{
    return null;
}

客户:

$.post('@Url.Action("Save", "Users")', {'IDs' : [1, 2, 3]}, function() {});

不工作。为什么??

【问题讨论】:

    标签: asp.net-mvc asp.net-mvc-3 model-binding


    【解决方案1】:

    您需要将数据作为 application/json 发送:

    $.ajax({
        type: 'post',
        url: '/Users/Save'
        data: JSON.stringify({'IDs' : [1, 2, 3]}),
        contentType: 'application/json; charset=utf-8',
        success: function() {
           // ...
        }
    });
    

    【讨论】:

    • Zoltan 的代码运行良好,不需要设置内容类型。
    【解决方案2】:

    您的代码发送IDs[]=1&amp;IDs[]=2&amp;IDs[]=3

    您需要发送IDs=1&amp;IDs=2&amp;IDs=3

    设置traditional:true参数使用传统的参数序列化风格。

    $.ajax({
        url: '@Url.Action("Save", "Users")',
        type: 'post',
        data: {'IDs' : [1, 2, 3]},
        traditional:true,
        success: function() {
            // ...
        }
    })
    

    【讨论】:

      【解决方案3】:

      这可能与我不久前遇到的问题相同。看看这个 SO 问题Post Array as JSON to MVC Controller

      【讨论】:

        【解决方案4】:

        你必须申请JSON.stringify

        $.post('@Url.Action("Save", "Users")', JSON.stringify({'IDs' : [1, 2, 3]}), function() {}); 
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2018-12-15
          • 1970-01-01
          相关资源
          最近更新 更多