【问题标题】:MVC Model binding with non sequential indexes具有非顺序索引的 MVC 模型绑定
【发布时间】:2015-11-04 02:02:28
【问题描述】:

我正在尝试将一组对象发布到控制器中的操作。如果我使用常规提交按钮发布,一切都会按预期工作,但是当我尝试通过 Ajax 发布时,列表总是空的。有任何想法吗?我的代码如下。

查看:

    @using (Html.BeginForm("Save", "Home", FormMethod.Post,  new { id = "myform" }))
    {
        
        <input type="text" name="Childs[0].Name" value="Name 1" />

        <input type="text" name="Childs[0].Age" value="12" />

        <input type="text" name="Childs.Index" value="0" />

        <input type="text" name="Childs[1].Name" value="Name 2" />

        <input type="text" name="Childs[1].Age" value="23" />

        <input type="text" name="Childs.Index" value="1" />

        <input type="text" name="AnotherProperty" value="111" />

        <input type="button" onclick="PostForm()" value="Test" />
    }

型号:

public class BinderTestModel
{
    public BinderTestModel()
    {
        Childs = new List<BinderTestChildModel>();
    }

    public int AnotherProperty { get; set; }

    public List<BinderTestChildModel> Childs { get; set; }
}

public class BinderTestChildModel
{
    public string Name { get; set; }

    public int Age { get; set; }
}

JS:

function PostForm()
{
        $.ajax({
        url: '@Url.Action("Save")',
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        datatype:'json',
        data: JSON.stringify($("#myform").serialize()),
        success: function()
        {
        },
        error: function (jqXHR, exception) {
            alert('Error message.');
        }
        });
}

谢谢,

贡萨洛

【问题讨论】:

    标签: .net json asp.net-mvc


    【解决方案1】:

    您需要删除 contentType: 'application/json; charset=utf-8', 选项而不是 .stringify() 数据,以便它使用默认的 application/x-www-form-urlencoded; charset=UTF-8 内容类型发布

    $.ajax({
        url: '@Url.Action("Save")',
        type: "POST",
        datatype:'json',
        data: $("#myform").serialize(),
        success: function()
        {
        },
        error: function (jqXHR, exception) {
            alert('Error message.');
        }
    });
    

    【讨论】:

    • 行得通,谢谢。如果我想包含不属于表单的其他数据怎么办?
    • 有很多选项,包括使用FormData(参考this answer)或使用jquery .param()(参考this answer
    【解决方案2】:

    如果您对非顺序索引有疑问,您应该添加隐藏输入并使用文本输入进行映射

    更多详情请查看 https://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx/

    <input type="hidden" name="products.Index" value="1" 
    <input type="text" name="products[1].Name" value="Salsa" />
    
    <input type="hidden" name="products.Index" value="3" 
    <input type="text" name="products[3].Name" value="Salsa" />

    【讨论】:

      猜你喜欢
      • 2011-08-07
      • 1970-01-01
      • 2013-12-16
      • 1970-01-01
      • 2011-07-08
      • 1970-01-01
      • 1970-01-01
      • 2015-02-17
      • 2019-07-22
      相关资源
      最近更新 更多