使用视图模型:
public class UserViewModel
{
public int UserId { get; set; }
public string Name { get; set; }
public boolean IsSelected { get; set; }
}
进而:
public class UsersController: Controller
{
public ActionResult Index()
{
var users = new UserViewModel[]
{
// TODO: obviously those could come from a database or something
new UserViewModel { UserId = 1, Name = "user 1" },
new UserViewModel { UserId = 2, Name = "user 2" },
new UserViewModel { UserId = 3, Name = "user 3" },
};
return View(users);
}
public ActionResult Index(UserViewModel[] users)
{
... you could inspect the IsSelected property of each user here
}
}
最后有一个强类型视图:
@model UserViewModel[]
@using (Html.BeginForm())
{
@for (var i = 0; i < Model.Length; i++)
{
<div>
@Html.HiddenFor(x => x[i].UserId)
@Html.HiddenFor(x => x[i].Name)
@Html.DisplayFor(x => x[i].Name)
@Html.CheckBoxFor(x => x[i].IsSelected)
</div>
}
<button type="submit">OK</button>
}
如果您已经有其他模型,那么,调整它并使用视图模型:
public class AssignUserViewModel
{
public UserViewModel[] Users { get; set; }
... some other properties that you already have
}
进而:
@model AssignUserViewModel
@using (Html.BeginForm())
{
@for (var i = 0; i < Model.Users.Length; i++)
{
<div>
@Html.HiddenFor(x => x.Users[i].UserId)
@Html.HiddenFor(x => x.Users[i].Name)
@Html.DisplayFor(x => x.Users[i].Name)
@Html.CheckBoxFor(x => x.Users[i].IsSelected)
</div>
}
... some other fields
<button type="submit">OK</button>
}
结论:始终使用视图模型。