我有一组“权限”。每个权限都具有三个属性:Id、Name 和 HasPermission。例如,考虑以下对象:
public class AccessPerm
{
int PermId {get;set;}
string PermName {get;set}
bool HasPerm {get;set;}
}
public class UserProfile
{
Collection<AccessPerm> UserPerms {get;set;}
}
所以我想使用 CheckBoxFor 帮助器来创建复选框,以便可以设置用户的权限。如果您选中该框,则 HasPerm 应该为 true。如果取消选中它,HasPerm 应该为 false。我遇到的问题是我没有找到将 PermId 和 HasPerm 属性绑定(bind)到复选框的方法。我使用以下代码绑定(bind) HasPerm 属性,但它没有用,因为我不知道 PermId。
<%
for(int ix=0; ix< Model.UserProfile.Perms.Count; ix++)
{
Html.CheckBoxFor(model => model.UserProfile.Perms[ix].HasPerm);
}
%>
这段代码确实绑定(bind)了HasPerm,并且值是正确的。但是,由于我没有 id,因此我无法对该值执行任何操作。请指教。
最佳答案
您可以将其包含为隐藏字段:
<% for(int ix = 0; ix < Model.UserProfile.Perms.Count; ix++) { %>
<%= Html.HiddenFor(model => model.UserProfile.Perms[ix].PermId) %>
<%= Html.CheckBoxFor(model => model.UserProfile.Perms[ix].HasPerm) %>
<% } %>
这样,您将在 POST Controller 操作中获得相同的列表,其中包含 id 以及是否已选择它。
关于c# - 如何绑定(bind)CheckBoxFor,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7557897/