控制器:
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
...
}
}
看法:
@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>
}
延伸阅读:Model Binding To a List
。