asp.net 中的多个下拉列表 mvc to actionresult

Multiple dropdownlist in asp.net mvc to actionresult

我正在使用 jquery 选择多个下拉列表。

我有多个来自所选下拉列表的值。

Html:

    @using (Html.BeginForm()) {
    <div class="editor-field" style="width:150px;">

    @Html.DropDownList("UserRole", null, new { @class = "chosen-select",@multiple="multiple",@placeholder="Lütfen Rol Seçiniz",@style="width:250px;"})

    </div>

    <input type="submit" value="Create" />
}

当我点击创建按钮按钮提交到下面的操作结果

[HttpPost]
public ActionResult AddUser(List<UserRole> UserRole) 
{
return view();
}

当我 post 时,UserRole 始终为 null

UserRole Class 以下属性

public int UserRoleID { get; set; }
public Nullable<int> FirmUserID { get; set; }
public Nullable<int> RoleID { get; set; }

我想念的地方我怎样才能选择多个下拉列表中的所有值?

任何帮助将不胜感激。

谢谢。

在您的方案中添加这样的列表框 @Html.ListBox("UserRole", null, new { @class = "chosen-select",@multiple="multiple",@placeholder="Lütfen Rol Seçiniz",@style="width:250px;"}) 以便您找到结果。

您需要使用 ListBox 来获得您想要的行为,而不是使用下拉列表。 ListBox 可以接受选定角色的数组,以及用于显示选定项目的 MultiSelectList。

我还建议使用视图模型,而不是依赖 ViewBag 来处理视图状态。扩展方法见CloneMatching

    @model UserRoleViewModel
    ...
    <div>
        <div class="editor-label">
            User Roles<br />(Ctrl-click for multiple)
        </div>
        <div class="editor-field">
            @Html.ListBoxFor(model => model.SelectedRoles,new MultiSelectList(model.AvailableRoles,"Id","Description",Model.SelectedRoles))
        </div>        
    </div>

用户角色视图模型:

 public class UserRoleViewModel {
     public User { get; set; }

     public List<int> SelectedRoles { get; set; }
     public List<Role> AvailableRoles { get; set; }
 }

用户角色控制器:

 public ActionResult Edit(int id) {
     var user = MyDbContext.Users.Find(id);
     var model = new Model {
         User = user;
         SelectedRoles = user.UserRoles.Select(userRole => userRole.Role.Id).ToList();
         AvailableRoles = MyDb.Context.Roles.ToList();
     };
     return View(model);
 }

 [HttpPost]
 public ActionResult Edit(UserRoleViewModel model) {
     if (ModelState.IsValid) {
         var user = MyDbContext.Users.Find(id).CloneMatching(model.User);
         user.UserRoles.Clear();
         MyDbContext.SaveChanges();

         foreach( var roleId in model.SelectedRoles) {
             users.UserRoles.Add(new UserRole {
                 UserId = user.Id,
                 RoleId = roleId
             });
         }
         MyDbContext.SaveChanges();
         return RedirectToAction("Index");
     }        
     return View(model);
 }