Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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.CheckBoxFor(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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
483 views
Welcome To Ask or Share your Answers For Others

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...