Search code examples
c#asp.net-mvcrazorviewbag

Razor: How to create a dropdown out of an IEnumerable<string> ViewBag property?


I have the following to render a view:

 public ActionResult CreateAlta()
        {
            ViewBag.RolesApp = new SQLRolerecord().GetAllRolesInApp();
            return View();
        }

How can generate a dropdown menu from the ViewBag property RolesApp? GetAllRolesInApp() returns an IEnumerable<string> and my attempt is below:

<div class="form-group">
     <label class="col-sm-2 control-label">Role: </label>
          <div class="col-sm-4">
            @Html.DropDownListFor("iroleeid", ViewBag.RolesApp, "--Select Role of User--");
          </div>
</div>

However this generates an error saying DropDownListFor does not exist in the HtmlHelper.

Thank You.


Solution

  • You can convert the list of strings to a list of SelectListItem's

    var roles = new SQLRolerecord().GetAllRolesInApp()
                                   .Select(f=>new SelectListItem { Value=f, Text = f}).ToList();
    ViewBag.Roles= roles ;
    

    Now in your view, you can use the DropDownList helper method.

    @Html.DropDownList("Roles")
    

    This will generate a select element with name and id property values set to "Roles". If you want those to be a different name, use this overload.

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

    This will create a dropdown with name and id property value set to "SelectedRole"

    Since we are setting the Value and Text of SelectListItem object to same string value, your select element option value and text will be same