开发者

How to bind CheckBoxFor

I have a collection of "permissions". Each permission would have three properties: Id, Name, and HasPermission. So as an example, consider the following object:

public class AccessPerm
{
  int PermId {get;set;}
  string PermName {get;set}
  bool HasPerm {get;set;}
}

public class UserProfile
{
  Collection<AccessPerm> UserPerms {get;set;}
}

So I want to use the CheckBoxFor helper to create checkboxes so that one can set the user's permissions. If you check the box, then HasPerm should be true. If you uncheck it, HasPerm should be false. The problem I am having is I don't see a way to bind both the PermId and the HasPerm properties to the checkbox. I used the following code to bind the HasPerm property, but it is not useful because I don't know the PermId.

<%
  for(int ix=0; ix< Model.UserProfile.Perms.Count; ix++)
  {
    Html.C开发者_高级运维heckBoxFor(model => model.UserProfile.Perms[ix].HasPerm);
  }
%>

This code does indeed bind HasPerm, and the value is correct. However, since I don't have the id, I can't do anything with the value. Please advise.


You could include it as hidden field:

<% 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) %>
<% } %>

This way you will get the same list in your POST controller action containing the id and whether it is selected.


You might try building a SelectList object and bind it to checkbox list.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜