Reputation: 379
I am using jquery choose multiple dropdownlist.
I have multiple values from selected dropdownlist.
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 Class properties below
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 ?
Any help will be appreciated.
Thanks.
Upvotes: 1
Views: 1097
Reputation: 2611
You'll need to use a ListBox to get the behavior you desire, instead of a dropdown list. The ListBox can accept an array of selected roles, along with a MultiSelectList to display the selected items.
I would also recommend using a view model, instead of relying upon the ViewBag for handing your view state. See CloneMatching for the extension method.
@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:
public class UserRoleViewModel {
public User { get; set; }
public List<int> SelectedRoles { get; set; }
public List<Role> AvailableRoles { get; set; }
}
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);
}
Upvotes: 1
Reputation: 530
in your scenario add the listbox like this @Html.ListBox("UserRole", null, new { @class = "chosen-select",@multiple="multiple",@placeholder="Lütfen Rol Seçiniz",@style="width:250px;"})
so you find the result.
Upvotes: 0