Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
493 views
in Technique[技术] by (71.8m points)

c# - 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.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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...