我的视图中有用户列表:
foreach (var user in (List<GetWorkDone.Model.Accounts.User>)ViewBag.users)
{
}
用户是:
public class User
{
public int UserId { get; set; }
public string Name { get; set; }
}
我需要在CheckBoxes中显示用户列表,并且只获取在ActionResult中选中的CheckBoxes:
public ActionResult AssignUser(List<User> users)
{
}
答案 0 :(得分:3)
使用视图模型:
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>
}
结论:使用视图模型 - 始终。