从mvc3 DropDown列表中渲染并选择数据

时间:2012-08-20 21:21:15

标签: c# asp.net-mvc-3

简单的情况

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

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

控制器:

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>

3 个答案:

答案 0 :(得分: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
)

答案 1 :(得分: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")

答案 2 :(得分:0)

如果要为用户选择多个用户组,则需要ListBoxFor

在ViewModel中添加一个字符串数组,以处理所选项目和所有组的集合属性。

public class UserViewModel
{
  //Other properties here
  public string[] SelectedGroups { get; set; }  
  public IEnumerable<SelectListItem> UserGroups{ get; set; }
}

GET操作方法中,获取用户组列表并分配给UserGroups proeprty 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" />
}

现在,当用户发布此表单时,您将获得ViewModel的SelectedGroups属性中的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);
}