1

简单的情况

一个对象用户有许多用户组。

我想在 mvc3 表单上实现编辑或创建操作以从下拉列表中选择用户组。

控制器:

private List<User> GetAllUsers()
{
    List<User> users;
    users = find all users to List...
    return users;
}

public ActionResult Edit(Guid Id)
{
   ViewBag.UserGroups = new SelectList(GetAllUsers(), "UserId", "Name");
   return View();
}

看法:

<div class="editor-label">
    @Html.LabelFor(model => model.UserGroupId, "UserGroupId")
</div>
<div class="editor-field">
    @Html.DropDownList(WHAT TO PUT HERE ?);
    @Html.ValidationMessageFor(model => model.UserGroupId)
</div>
4

3 回答 3

5

哦,请使用视图模型,剪掉那个 ViewBag 的废话,每次看到它都让我恶心。

public class UserViewModel
{
    public int UserGroupId { get; set; }
    public IEnumerable<SelectListItem> UserGroups { get; set; }
}

进而:

public ActionResult Edit(Guid Id)
{
    var model = new UserViewModel
    {
        UserGroups = new SelectList(GetAllUsers(), "UserId", "Name")
    }
    return View(model);
}

在视图中:

@model UserViewModel
...
<div class="editor-label">
    @Html.LabelFor(model => model.UserGroupId, "UserGroupId")
    </div>
    <div class="editor-field">
        @Html.DropDownListFor(x => x.UserGroupId, Model.UserGroups);
        @Html.ValidationMessageFor(model => model.UserGroupId)
    </div>
</div>

但如果你想让我生病并保留 ViewCrap:

@Html.DropDownListFor(
    x => x.UserGroupId, 
    (IEnumerable<SelectListItem>)ViewBag.UserGroups
)
于 2012-08-20T21:25:02.217 回答
0

在控制器上:

ViewBag.UserGroupId = new SelectList(GetAllUsers(), "UserId", "Name");

在观点上:

@Html.DropDownListFor(m => m.UserGroupId, null);

如果你想要类型安全,你可以使用这个辅助方法:

void SetSelectList<TModel, TProperty>(
   TModel model, 
   Expression<Func<TModel, TProperty>> propertySelector, 
   IEnumerable<SelectListItem> list) {

   this.ViewData[ExpressionHelper.GetExpressionText(propertySelector)] = list;
}

并像这样使用它:

SetSelectList(model, m => m.UserGroupId, new SelectList(GetAllUsers(), "UserId", "Name"));


额外提示:ToDictionary在创建SelectList实例时用于额外的类型安全:

new SelectList(GetAllUsers().ToDictionary(u => u.UserId, u => u.Name), "Key", "Value")
于 2012-08-20T21:33:11.863 回答
0

如果要为用户选择多个用户组,则需要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);
}
于 2012-08-20T21:35:51.260 回答