I want to bind a List to CheckBox and get the selected values. I need to display two such Checkbox tables and have to retrieve both the IDs.
Below is my ViewModel
I don't want to appear like I'm taking credit for James excellent work, but a new answer is all I can do. For reasons I do not understand, my edit that corrected compile errors in the code were rejected as not correcting critical issues. So I post this as a complete working answer.
The Models:
public class UserRole
{
public int RoleID {get; set;}
public string RoleName {get; set;}
public bool Selected {get; set;}
}
public class UserSecurity
{
public int SecurityID {get; set;}
public string SecurityName {get; set;}
public bool Selected {get; set;}
}
public class UserRoleAndSecurityModel
{
public List RoleMaster {get; set;}
public List SecurityMaster {get; set;}
}
And the view:
@model UserRoleAndSecurityModel
@using (Html.BeginForm())
{
User Role
@for (int i = 0; i < Model.RoleMaster.Count; i++)
{
@Html.CheckBoxFor(m => m.RoleMaster[i].Selected)
@Html.HiddenFor(m => m.RoleMaster[i].RoleId)
@Html.LabelFor(m => m.RoleMaster[i].Selected,
Model.RoleMaster[i].RoleName)
}
Role Security
@for (int i = 0; i < Model.SecurityMaster.Count; i++)
{
@Html.CheckBoxFor(m => m.SecurityMaster[i].Selected)
@Html.HiddenFor(m => m.SecurityMaster[i].SecurityId)
@Html.LabelFor(m => m.SecurityMaster[i].Selected,
Model.SecurityMaster[i].SecurityName)
}