使用視圖模型:
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>
}
結論:使用視圖模型 - 總是。
而你的視圖強烈鍵入哪個模型? – Jorge 2012-08-10 15:07:23
這是用另一個模型輸入我發佈用戶到AssignUser ActionResult – 2012-08-10 15:11:22