0

I'm trying to implement a Dropdownlist that displays data from database. The code for my implementation is as follows:

View

<div class="form-group">
    @Html.Label("Select Your User Type", new { @class = "col-md-2 control-label" })
    <div class="col-md-10">
        @Html.DropDownList("Drop")
    </div>
</div>

Controller

ViewBag.Drop = new SelectList(db.Roles, "Name", "Name");

I have checked that many online tutorials uses this method. However, whenever I try to save the information, it gives off the error as follows:

enter image description here

I checked the datatype for the ViewBag.Drop and it was System.Web.Mvc.SelectListItem datatype instead of the IEnumerable<SelectListItem needed for the Html.DropDownlist helper function.

What should I do and how come it changes the type to System.Web.Mvc.SelectListItem???

Pow4Pow5
  • 501
  • 2
  • 8
  • 22

1 Answers1

1

You changed the type when you created the list as a SelectList.

What would happen if you did this?:

[ Controller ]

var Drop = db.Roles.ToList();
ViewBag.Drop = Drop;

[ View ]

@Html.DropDownListFor(model => model.RoleName, new SelectList(@ViewBag.Drop, "Name", "Name"), new { htmlAttributes = new { @class = "form-control" } })

Where the Drop declaration creates an IEnumerable List of IdentityRole, and it's passed to the View via the ViewBag. Where (assuming if you're using a ViewModel with a property named RoleName), you would be selecting the value for the RoleName from the List.

Here you're creating a SelectList and telling it what member of the Drop list to use for the value and what member value to show for selection.

nocturns2
  • 663
  • 10
  • 17