0

This is my controller

[AllowAnonymous]
        public ActionResult Register()
        {
            ViewBag.Name = new SelectList(context.Roles.ToList(), "Name", "Name");
            return View();
        }

This is my Create view part

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

i can load the form with drop down. but when I am try to save the record it gives an error "The ViewData item that has the key 'Name' is of type 'System.String' but must be of type 'IEnumerable'."

  • possible duplicate of [ASP.NET MVC Dropdown List From SelectList](http://stackoverflow.com/questions/20242981/asp-net-mvc-dropdown-list-from-selectlist) – Jamie Rees Jul 29 '15 at 10:43

1 Answers1

1

Do this:

[AllowAnonymous]
public ActionResult Register()
{
        var items = new List<SelectListItem>();
        foreach (var role in context.Roles)
        {
            items.Add(new SelectListItem {Text = role.Name, Value = role.Value});
        }

        var result = new SelectList(items);
        ViewBag.Name = result;
        return View();
}

View

 @Html.DropDownList("Name",ViewBag.Name)

But can I suggest that you avoid ViewBag and use strongly typed models.

Look here

Jamie Rees
  • 7,973
  • 2
  • 45
  • 83