ITWorker ITWorker - 2 months ago 16
ASP.NET (C#) Question

Razor default selection in dropdownlist?

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.

Answer

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?

Comments