MVC 3.0中的默认模型绑定器真的能够处理非顺序索引(对于简单和复杂模型类型)吗?我遇到的帖子建议它应该,但在我的测试中,它似乎不是。
给定的回发值:
items[0].Id = 10
items[0].Name = "Some Item"
items[1].Id = 3
items[1].Name = "Some Item"
items[4].Id = 6
items[4].Name = "Some Item"以及一种控制器方法:
public ActionResult(IList<MyItem> items) { ... }加载的唯一值是项0和1;项4被忽略。
我已经看到了许多生成自定义索引(Model Binding to a List)的解决方案,但是它们似乎都是针对以前版本的MVC,而且大多数都有点“笨手笨脚”。
我是不是遗漏了什么?
发布于 2011-12-22 09:01:24
我有这个工作,你必须记得添加一个通用的索引隐藏输入,如你的参考文章中所解释的那样:
name = Items.Index的隐藏输入是关键部分
<input type="hidden" name="Items.Index" value="0" />
<input type="text" name="Items[0].Name" value="someValue1" />
<input type="hidden" name="Items.Index" value="1" />
<input type="text" name="Items[1].Name" value="someValue2" />
<input type="hidden" name="Items.Index" value="3" />
<input type="text" name="Items[3].Name" value="someValue3" />
<input type="hidden" name="Items.Index" value="4" />
<input type="text" name="Items[4].Name" value="someValue4" />希望这能有所帮助
发布于 2014-01-24 12:11:02
这个辅助方法源自Steve Sanderson的方法,简单得多,可以用来锚定集合中的任何项,而且它似乎可以与MVC模型绑定一起工作。
public static IHtmlString AnchorIndex(this HtmlHelper html)
{
var htmlFieldPrefix = html.ViewData.TemplateInfo.HtmlFieldPrefix;
var m = Regex.Match(htmlFieldPrefix, @"([\w]+)\[([\w]*)\]");
if (m.Success && m.Groups.Count == 3)
return
MvcHtmlString.Create(
string.Format(
"<input type=\"hidden\" name=\"{0}.index\" autocomplete=\"off\" value=\"{1}\" />",
m.Groups[1].Value, m.Groups[2].Value));
return null;
}例如,只需在EditorTemplate中调用它,或者在其他任何地方生成输入,如下所示生成索引锚定隐藏变量(如果适用)。
@model SomeViewModel
@Html.AnchorIndex()
@Html.TextBoxFor(m => m.Name)
... etc.我认为它比Steve Sanderson的方法有一些优势。
Items是视图模型上的IEnumerable<T>属性,则以下内容将按预期工作:<ul id="editorRows" class="list-unstyled"> @Html.EditorFor(m => m.Items) @* Each item will correctly anchor allowing for dynamic add/deletion via Javascript *@ </ul>
唯一的缺点是,如果要绑定的根模型是可枚举的(即Action方法本身的参数,而不仅仅是参数对象图中更深的某个属性),则绑定将在第一个非顺序索引处失败。不幸的是,DefaultModelBinder的.Index功能只适用于非根对象。在这种情况下,您唯一的选择仍然是使用上面的方法。
发布于 2011-12-22 11:57:01
您引用的文章是一篇旧文章(MVC2),但据我所知,这仍然是使用默认模型绑定器对绑定集合进行建模的实际方法。
如果你想像Bassam说的那样进行非顺序的索引,你需要指定一个索引器。索引器不需要是数字。
为此,我们使用Steve Sanderson's BeginCollectionItem Html Helper。它会自动将索引器生成为Guid。我认为这是一种比使用数字索引器更好的方法,当您的集合项目HTML是非连续的时候。
https://stackoverflow.com/questions/8598214
复制相似问题