[英]Multiple dropdownlist in asp.net mvc to actionresult
I am using jquery choose multiple dropdownlist. 我正在使用jquery选择多个dropdownlist。
I have multiple values from selected dropdownlist. 我从选定的下拉列表中有多个值。
Html: 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" />
}
When i click to create button button submits to below actionresult 当我单击创建按钮时,按钮将提交给以下动作结果
[HttpPost]
public ActionResult AddUser(List<UserRole> UserRole)
{
return view();
}
UserRole is always null when i post it 当我发布UserRole时,它始终为null
UserRole Class properties below 下面的UserRole类属性
public int UserRoleID { get; set; }
public Nullable<int> FirmUserID { get; set; }
public Nullable<int> RoleID { get; set; }
Where i miss how can i get selected all values in multiple dropdownlist ? 我在哪里想念如何在多个dropdownlist中选择所有值?
Any help will be appreciated. 任何帮助将不胜感激。
Thanks. 谢谢。
在您的方案中,像这样添加列表框@Html.ListBox("UserRole", null, new { @class = "chosen-select",@multiple="multiple",@placeholder="Lütfen Rol Seçiniz",@style="width:250px;"})
以便您找到结果。
You'll need to use a ListBox to get the behavior you desire, instead of a dropdown list. 您需要使用ListBox来获得所需的行为,而不是下拉列表。 The ListBox can accept an array of selected roles, along with a MultiSelectList to display the selected items. ListBox可以接受一系列选定角色,以及一个MultiSelectList来显示选定项。
I would also recommend using a view model, instead of relying upon the ViewBag for handing your view state. 我还建议使用视图模型,而不是依赖ViewBag来处理视图状态。 See CloneMatching for the extension method. 有关扩展方法,请参见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>
UserRoleViewModel: UserRoleViewModel:
public class UserRoleViewModel {
public User { get; set; }
public List<int> SelectedRoles { get; set; }
public List<Role> AvailableRoles { get; set; }
}
UserRoleController: UserRoleController:
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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.