asp.net-mvc - 模型联编程序不会将 json 转换为 IEnumerable<T>

标签 asp.net-mvc json modelbinder

我正在通过 jquery ajax post 将 json 数据发送到我的 Controller 操作。我的操作中的 IEnumerable 始终为空。

我的 json 是错误的还是为什么模型绑定(bind)器没有将 json 转换为 IEnumerable?

public ActionResult Update(IEnumerable<Teststep> teststeps)
{
   //
}

$.ajax({
            url: '@Url.Action("Update", "Teststep")',
            type: 'POST',
            data: [{ "errortext": "oh something bad happended.", "unitid": "10" }, { "errortext": "you got it man.", "unitid": "20"}],
            success: function (response) {
                debugger;
                if (response.success) {
                    dlg.dialog("close");
                    // Update UI

                }
                else {
                    // Reload the dialog with the form to show model/validation errors 
                    dlg.html(response);
                }
            }
        });

public class Teststep
{

 [HiddenInput(DisplayValue = false)]
 public int UnitId { get; set; }    

 public string ErrorText { get; set; }  

 // some other props removed for readability   

}

最佳答案

为了让集合(数组、ienumerables 等)正确地通过模型绑定(bind)器传递到操作方法,我总是必须在 ajax 调用上设置传统的:true 选项:

$.ajax({
    url: '@Url.Action("Update", "Teststep")',
    type: 'POST',
    traditional: true,
    ...

关于asp.net-mvc - 模型联编程序不会将 json 转换为 IEnumerable<T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10899530/

相关文章:

c# - global.asax 中的 MVC web 应用程序,当 session 超时时如何获取 cookie 值

asp.net-mvc-3 - bindmodel vs createmodel asp mvc 3

asp.net - 如何使 Controller 接受来自正文的发布数据以及 MVC 6 ASP.NET 5 中的 URL

c# - 在 .Net Core 中使用 smtp 服务器发送电子邮件?

javascript - 如何获取第二个定义的单选按钮值?

java - 如何在一行代码中配置 JacksonJaxbJsonProvider?

c# - 德国文化 - 用逗号从 JSON 中获取双数

asp.net-mvc-3 - 将 MVC 2 升级到 MVC3 获取模型绑定(bind)器异常

c# - 在请求期间放弃 session

c# - 获取 JSON 对象节点