如果要为用户选择多个用户组,则需要ListBoxFor
.
在 ViewModel 中添加一个字符串数组来处理所有组的选定项目和一个集合属性。
public class UserViewModel
{
//Other properties here
public string[] SelectedGroups { get; set; }
public IEnumerable<SelectListItem> UserGroups{ get; set; }
}
在您的GET
操作方法中,获取用户组列表并分配给UserGroups
属性 pf UserViewModel ViewModel 对象。
public ActionResult CreateUser()
{
var vm = new UserViewModel();
//The below code is hardcoded for demo. you mat replace with DB data.
vm.UserGroups= new[]
{
new SelectListItem { Value = "1", Text = "Group 1" },
new SelectListItem { Value = "2", Text = "Group 2" },
new SelectListItem { Value = "3", Text = "Group 3" }
};
return View(vm);
}
现在在你的视图中,它是强类型的UserViewModel
类,
@model UserViewModel
<h2>Create User </h2>
@using (Html.BeginForm())
{
@Html.ListBoxFor(s => s.SelectedGroups,
new SelectList(Model.UserGroups, "Value", "Text"))
<input type="submit" value="Save" />
}
SelectedGroups
现在,当用户发布此表单时,您将在 ViewModel的属性中获得 Selected Items 值
[HttpPost]
public ActionResult CreateUser(UserViewModel model)
{
if (ModelState.IsValid)
{
string[] groups= model.SelectedGroups;
//check items now
//do your further things and follow PRG pattern as needed
}
//reload the groups again in the ViewModel before returning to the View
return View(model);
}