问题描述
我认为这个问题适用于任何的为HTML辅助,但我的具体问题是使用CheckBoxFor ...
I believe this question applies to any of the "For" Html helpers, but my specific problem is using CheckBoxFor...
我有一个模型,它是IEnumerable类型,其中的权利是一个简单的POCO。这种模式实际上是我创建了一个EditorTemplate一个更大的模型的属性。这里是我的模型的大局观:
I have a model that is of type IEnumerable, where rights is a simple POCO. This model is actually a property of a bigger model that I created an EditorTemplate for. Here is the bigger picture of my model:
public class bigmodel
{
public string Title {get; set;}
public string Description {get; set;}
[UIHint("ListRights")]
public IEnumerable<rights> Rights {get;set;}
}
public class rights
{
public bool HasAccess {get; set;}
public string Description {get;set;}
}
我创建了一个名为ListRights我的主视图使用editortemplate。为例如:&lt;%= Html.EditorFor(M => m.Rights)%>。
I created an editortemplate called "ListRights" that my main view uses. For example: <%=Html.EditorFor(m => m.Rights) %>.
在ListRights.ascx,我想code是这样的:
In ListRights.ascx, I want code like this:
<table>
<% foreach(rights access in Model)
{ %>
<tr>
<td>
<%=Html.CheckBoxFor( access ) %>
</td>
<td>
<%=access.Description %>
</td>
</tr>
<% } %>
</table>
我知道CheckBoxFor行不工作,但我想要做的事产生相同的结果,仿佛进入了模型上的属性。
I know the CheckBoxFor line does not work, but I want to do something that generates the same result, as if access was a property on the model.
在上面的例子中,我想一切autobind的帖子。
In the above example, I would like everything to autobind on post.
我试图用伪造类似这样code中的复选框,但并不autobind:
I've tried faking the CheckBox with code similar to this, but it doesn't autobind:
<table>
<% for(int i=0; i < Model.Count(); i++)
{ %>
<tr>
<td>
<%=Html.CheckBox(string.Format("[{0}].HasAccess",i), Model.ElementAt(i).HasAccess)%>
</td>
<td>
<%=access.Description %>
</td>
</tr>
<% } %>
</table>
有什么建议?
推荐答案
我找到了答案,通过使用由史蒂夫·桑德森博客文章在的
I found the answer by using a blog post by Steve Sanderson at http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
使用Html.BeginCollectionItem在我的处境的工作。
Using "Html.BeginCollectionItem" worked in my situation.
我创建了权利的EditorTemplate(在我的例子)。然后加入史蒂夫的BeginCollectionItem该模板。我打电话使用Html.RenderPartial模板在史蒂夫的博客建议。
I created an EditorTemplate for rights (in my example). Then added Steve's BeginCollectionItem to that template. I called the template using Html.RenderPartial as suggested in Steve's blog.
我想用Html.EditorFor(M => m.item),但是,这并不工作,因为产品在foreach,而不是在模型中。可以在这种情况下使用EditorFor
I wanted to use Html.EditorFor(m => m.item), but that doesn't work because item is in the ForEach and not in the model. Could EditorFor be used in this case?
这篇关于foreach所在ASP.Net MVC IEnumerable的财产和CheckBoxFor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!