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
Just to flesh out my comment above...
For a checkboxList - the viewmodel should include both an identifier property, and boolean selected property. If it doesn't already then either extend or create a new ViewModel class to fulfil this purpose - map your existing model to this specific viewmodel.
i.e. - Your Model Class(es)
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;}
}
Your View:
Note that in addition to the checkboxes Html.HiddenFor()
has been included for each of the UserRole/UserSecurity ID properties, which allows MVC to bind the ID properties after postback.
@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)
}
and your controller should now use the new model above too!