带有表单和列表的 MVC 3:默认模型绑定器和 EditorFor
模型:
public class MyObject
{
public IList<Entry> Entries;
}
public class Entry
{
public string Name { get; set; }
}
如果我使用默认的 EditorFor(model => model.Entries),则名称/id 值为:
<input type="text" value="" name="Entries[0].Name" id="Entries_0__Name">
如果相反,我想创建一个这样的 EditorFor 模板:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<CMS.Models.MyObject>>" %>
<div class="list">
<%
for (int i = 0; i < Model.Count; i++)
{ %>
<div class="object" id="<%: i %>">
<%: Html.EditorFor(model => Model[i]) %>
<%: Html.ValidationMessageFor(model => Model[i]) %>
</div>
<% } %>
</div>
发出的名称/id 值为:
<input type="text" value="" name="Entries.[0].Name" id="Entries__0__Name">
所以名称有一个属性名称和 [0] 之间的句点和 id 在索引号左侧有一个额外的下划线。这不适用于默认模型绑定器。有没有一种方法可以与默认模型绑定器一起使用?
The Model:
public class MyObject
{
public IList<Entry> Entries;
}
public class Entry
{
public string Name { get; set; }
}
If I use the default EditorFor(model => model.Entries) the name/id values are:
<input type="text" value="" name="Entries[0].Name" id="Entries_0__Name">
If instead I want to create an EditorFor template like this:
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<List<CMS.Models.MyObject>>" %>
<div class="list">
<%
for (int i = 0; i < Model.Count; i++)
{ %>
<div class="object" id="<%: i %>">
<%: Html.EditorFor(model => Model[i]) %>
<%: Html.ValidationMessageFor(model => Model[i]) %>
</div>
<% } %>
</div>
The emitted name/id values are:
<input type="text" value="" name="Entries.[0].Name" id="Entries__0__Name">
So the name has a period between the property name and [0] and the id has an extra underscore to the left of the index number. This doesn't work with the default model binder. Is there a way to do this that does work with the default model binder?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为您可以使用模板完成大部分工作,而不必显式迭代列表,这似乎会导致模型绑定程序出现问题。
尝试制作这些共享编辑器模板:
MyObject 编辑器模板
条目编辑器模板
我唯一还没弄清楚的是如何在 id 属性中获取正确的值div,因此有问号。最后需要注意的是,我在家,所以我还没有真正尝试过这个。
I think you can do most of this using templates without having to explicitly iterate over the list, which seems to be causing your problems with the model binder.
Try making these shared editor templates:
MyObject Editor Template
Entry Editor Template
The only thing I haven't figured out yet is how to get the correct value in the id attribute of the div, hence the question marks. Final caveat is that I'm at home so I haven't actually tried this.