MVC ModelBinding to a List - Losing Items

dkn*_*ack 2 asp.net-mvc asp.net-mvc-3

Lets say a have the following Model

public class FirstModel
{
    public List<SecondModel> SecondModels { get; set; }
}

public class SecondModel
{
    public string Value { get; set; }
}
Run Code Online (Sandbox Code Playgroud)

And this View

@model FirstModel

....
<input name="SecondModels[0].Value" value="test1"/>
<input name="SecondModels[1].Value" value="test2"/>
<input name="SecondModels[2].Value" value="test3"/>
...
Run Code Online (Sandbox Code Playgroud)

The Modelbinding works good. I get the complete Model to my ActionMethod.

But if i remove the item in the middle using, for example, jQuery.

<input name="SecondModels[0].Value" value="test1"/>
<input name="SecondModels[2].Value" value="test3"/>
Run Code Online (Sandbox Code Playgroud)

i lost the SecondModels[2] because the ModelBinder is unable to bind. So i get only the first ("test1").

是否有另一个可以正确绑定此语法的语法或CustomModelBinder,或者input在删除项目后是否需要替换名称?

提前非常感谢您!

tug*_*erk 5

您可以在此处使用ASP.NET MVC的非顺序模型绑定功能。对于您的情况,您需要以下内容:

<input type="hidden" name="SecondModels.Index" value="0" />
<input name="SecondModels[0].Value" value="test1"/>

<input type="hidden" name="SecondModels.Index" value="2" />
<input name="SecondModels[2].Value" value="test3"/>
Run Code Online (Sandbox Code Playgroud)

有关更多信息,请查看Phil Haack博客文章中的非顺序索引部分:

模型绑定到列表