render and select data from mvc3 DropDown list

2019-04-16 16:37发布

问题:

Simple situation

One object User have many UserGroups.

I want to implement on mvc3 form editing or creating action to select UserGroups from drop down.

Controller:

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();
}

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>

回答1:

Oh please use a view model, cut that crap of a ViewBag, makes me sick every time I see it.

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

and then:

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

and in the view:

@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>

but if you wanna make me sick and keep the ViewCrap:

@Html.DropDownListFor(
    x => x.UserGroupId, 
    (IEnumerable<SelectListItem>)ViewBag.UserGroups
)


回答2:

On the controller:

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

On the view:

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

If you want type-safety instead you can use this helper method:

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

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

and use it like this:

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


Bonus tip: Use ToDictionary for extra type-safety when creating the SelectList instance:

new SelectList(GetAllUsers().ToDictionary(u => u.UserId, u => u.Name), "Key", "Value")


回答3:

If you want to select Multiple UserGroups for a User, you need ListBoxFor.

Add a string array in your ViewModel to handle the selected items and a collection property for all Groups.

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

In your GET action method, Get a list of UserGroups and assign to the UserGroups proeprty pf UserViewModel ViewModel object.

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);
}

Now in your View, Which is strongly typed to UserViewModel class,

@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" />
}

Now when user posts this form, you will get the Selected Items value in the SelectedGroups property of the ViewModel

[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);
}