Setting selected value in dropdown list
Hello every one i have strange bug with dropdownlist on one of the pages!
I used code 开发者_运维问答such as this for 3 dropdownlists:
//GetTypes returns collection of all availibale types from database
ViewData["Types"] = new SelectList(dataManager.IssueTypes.GetTypes(), "Id", "Title", issue.Type);
and it works great!
But when i used it like this:
// GetRoles returns collection of all availibale roles
ViewData["Roles"] = new SelectList(dataManager.Membership.GetRoles(), "RoleId", "RoleName",
dataManager.Membership.GetUserRole(id));
it always shows default value! I looked trough this code with debuger many times but everithing seems fine! Will be grateful for any kind of help!
View code:
%: Html.DropDownList("RoleId", ViewData["Roles"] as IEnumerable<SelectListItem>)%>
How about using view models instead of ViewData
? Everytime I see someone using ViewData
I feel myself in the obligation to point this out as personally I consider as best practices.
So start with defining a view model that will be used by your view:
public class RolesViewModel
{
public string SelectedRoleId { get; set; }
public IEnumerable<SelectListItem> Roles { get; set; }
}
Now let's move on to the controller action that will populate this view model and pass it to the view:
public ActionResult Foo(string id)
{
var model = new RolesViewModel
{
SelectedRoleId = dataManager.Membership.GetUserRole(id),
Roles = dataManager.Membership.GetRoles().Select(x => new SelectListItem
{
Value = x.RoleId,
Text = x.RoleName
})
};
return View(model);
}
OK, now you should ensure that SelectedRoleId
represents a string value which is present in the Roles
collection. This is what will preselect the dropdown list.
And finally the strongly typed view:
<%= Html.DropDownListFor(
x => x.SelectedRoleId,
new SelectList(Model.Roles, "Value", "Text")
)%>
I don't know what type your dataManager.Membershop.GetUserRole(id) returns?
But you need to change the 4th parameter in this call:
ViewData["Roles"] = new SelectList(dataManager.Membership.GetRoles(), "RoleId", "RoleName",
dataManager.Membership.GetUserRole(id));
To something like:
ViewData["Roles"] = new SelectList(dataManager.Membership.GetRoles(), "RoleId", "RoleName",
dataManager.Membership.GetUserRole(id).RoleId);
Notice the RoleId at the end? The object you specify as the selected item, should be the value of the item's Value property - not the entire object.
精彩评论