Binding check box values to list in the model mvc
asp.net-mvc, asp.net-mvc-3
Solution
Controller:
public class HomeController : Controller
{
public ActionResult Index()
{
var model = new UserRightsViewModel
{
// Obviously those could come from some data source
ScreenRights = new[]
{
new ScreenRight { UserName = "Robert", Select = true, Add = false, Edit = false },
new ScreenRight { UserName = "John", Select = true, Add = true, Edit = false },
new ScreenRight { UserName = "Mike", Select = true, Add = true, Edit = false },
new ScreenRight { UserName = "Allan", Select = true, Add = true, Edit = true },
new ScreenRight { UserName = "Richard", Select = false, Add = false, Edit = false },
}.ToList()
};
return View(model);
}
[HttpPost]
public ActionResult Index(UserRightsViewModel model)
{
// The view model will be correctly populated here
// TODO: do some processing with them and redirect or
// render the same view passing it the view model
...
}
}
View:
@model UserRightsViewModel
@using (Html.BeginForm())
{
<table>
<thead>
<tr>
<th>User Id</th>
<th>Select</th>
<th>Add</th>
<th>Edit</th>
</tr>
</thead>
<tbody>
@for (int i = 0; i < Model.ScreenRights.Count; i++)
{
<tr>
<td>
@Html.DisplayFor(x => x.ScreenRights[i].UserName)
@Html.HiddenFor(x => x.ScreenRights[i].UserName)
</td>
<td>
@Html.CheckBoxFor(x => x.ScreenRights[i].Select)
</td>
<td>
@Html.CheckBoxFor(x => x.ScreenRights[i].Add)
</td>
<td>
@Html.CheckBoxFor(x => x.ScreenRights[i].Edit)
</td>
</tr>
}
</tbody>
</table>
<button type="submit">OK</button>
}
Further reading: `Model Binding To a List`.
Problem
My problem is I have to create a layout like the following Using MVC to assign rights to the user. Now there is no problem in creating the check boxes I'll create it using the list of users. but while submitting the form i should submit it to the list like below. ``` public class UserRightsViewModel { public UserRightsViewModel() { _screenrights = new List<ScreenRight>(); } public String Id { get; set; }// Role Name List<ScreenRight> _screenrights; public List<ScreenRight> ScreenRights { get { return _screenrights; } set { _screenrights = value; } } } ``` definition for screenRight is below ``` public class ScreenRight { public String UserName { get; set; } public Boolean Select{ get; set; } public Boolean Add{ get; set; } public Boolean Edit{ get; set; } ,,, } ``` Now while submitting the form how can i post it to the controller in the right format.