Reputation: 4496
Hello I created a SelectList
:
ViewBag.RoleId = new SelectList(unitOfWork.roleRepository.Get(), "Id", "RoleName", user.RoleId);
As you can see The SelectedValue
property is set for this SelectList
.
I'm binding it to DropDownList
like in this sample:
@Html.DropDownList("RoleId", null, new { @class = "form-control" })
List is populated but selected value is always first value in the list instead of user.RoleId
from controller.
How to modify initialization of the Html helper to make it work?
Upvotes: 0
Views: 47
Reputation: 7506
The SelectList
constructor expects the object to be selected as the 4th parameter. This object cannot be selected automatically in the constructor by specifying the value of one of its properties. The correct version is this:
var data = unitOfWork.roleRepository.Get();
ViewBag.RoleId = new SelectList(data,
"Id",
"RoleName",
data.Where(x => x.Id == user.RoleId).FirstOrDefault());
Upvotes: 1
Reputation: 42
Bind the dropdownlist as :
@Html.DropDownList("Id", (SelectList)ViewBag.RoleId, "Select Item", new { @class = "form-control" })
Upvotes: 0