1

I have the following declaration in Razor:

@Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>, ViewBag.CurrentUserRole as string, new { @class = "form-control" }), and it results in a drop-down that looks as follows on page load:

enter image description here

And when I click on the dropdown arrow, I see:

enter image description here

So basically, the User Role is duplicated. How can I change this so that instead of making a new duplicate element, it defaults to the element it is supposed to be? Basically, since ViewBag.RolesEdit is a list, and ViewBag.CurrentUserRole is guaranteed to have an element that is equal to exactly one item in the afformentioned list, how can I loop through the list to compare each other and set the default?

Thank You.

ITWorker
  • 965
  • 2
  • 16
  • 39
  • You might want to look at this [answer](http://stackoverflow.com/a/37819577/296861). – Win Sep 20 '16 at 20:27
  • Is `CurrentUserRole` set to the `text` `RegularUser` or is set to the `value` corresponding to `RegularUser`? – stephen.vakil Sep 20 '16 at 20:43
  • @stephen.vakil it is set to the `text` in the controller as follows: `ViewBag.CurrentUserRole = user.UserRole();` where `user` is a type of user from the Identity framework. – ITWorker Sep 20 '16 at 20:48
  • @Win I will keep it in mind when it comes time to refactor the code. – ITWorker Sep 20 '16 at 20:48

1 Answers1

2

When using Html.DropDownList helper method, To set one option to be pre selected, you just need to set the value of that option to the the ViewBag dictionary with the same key used to generate the SELECT element.

@Html.DropDownList("SelectedRole", ViewBag.RolesEdit as List<SelectListItem>)

Assuming your action method is setting ViewBag.SelectedRole to the value of the option you want to select.

ViewBag.RolesEdit= new List<SelectListItem>{     
   new SelectListItem { Value="Administrator", Text="Administrator"},
   new SelectListItem { Value="Employees", Text="Employees"},
   new SelectListItem { Value="RegularUser", Text="Regular User"},
}
ViewBag.SelectedRole  ="RegularUser";
return View();

If you prefer to use Html.DropDownListFor helper method with a strongly typed view and view model, you can follow this post

What is the best ways to bind @Html.DropDownListFor in ASP.NET MVC5?

Community
  • 1
  • 1
Shyju
  • 214,206
  • 104
  • 411
  • 497
  • Thanks, this worked. I used `ViewBag.SelectedRole = user.UserRole();` instead of the hardcoding it as in your answer. – ITWorker Sep 20 '16 at 21:06