MVC模型与非顺序索引的绑定

时间:2015-11-04 02:02:29

标签: .net json asp.net-mvc

我试图将一组对象发布到控制器内的动作中。如果我使用常规提交按钮发布一切都按预期工作,但是当我尝试通过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" />
    }
&#13;
&#13;
&#13;

型号:

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.');
        }
        });
}

谢谢,

Gonzalo

2 个答案:

答案 0 :(得分:0)

您需要删除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.');
    }
});

答案 1 :(得分:0)

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

有关更多详细信息,请检查 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" />

相关问题