ビューモデルを使用する:
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>
}
結論:ビューモデルを使用する-常に。