0

I am trying to create a dropdown list in my .Net MVC project.

This is how my Controller looks like

public ActionResult Register()
    {
        ViewBag.Name = new SelectList(context.AspNetRoles.ToList(), "Id", "Name");

        return View();
    }

And this is how my View looks like

<div class="form-group">
    @Html.LabelFor(model => model.Name, "Name", htmlAttributes: new { @class = "control-label col-md-2" })
    <div class="col-md-10">
        @Html.DropDownList("Name", ViewBag.Name as SelectList)
        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })
    </div>
</div>

The problem what i am facing is that when i execute my code i get this Excpetion

The ViewData item that has the key 'Name' is of type 'System.String' but must be of type 'IEnumerable'.

As i am Newbie to MVC,I dont know why i am getting this exception.Any help would be appreciated. Thanks in advance. Happy Coding!

  • 1
    Because you did not repopulate the `SelectList` in the POST method before you returned the view. But everything your doing here is bad practice - using `ViewBag`, using the same name for the property your binding to and the `ViewBag` property, using `DropDownList()` instead of `DropDownListFor()`. –  Jun 21 '16 at 23:37
  • Recommend your read the answers [here](http://stackoverflow.com/questions/34366305/the-viewdata-item-that-has-the-key-xxx-is-of-type-system-int32-but-must-be-o) and [here](http://stackoverflow.com/questions/37161202/will-there-be-any-conflict-if-i-specify-the-viewbag-name-to-be-equal-to-the-mode/37162557#37162557) –  Jun 21 '16 at 23:37

0 Answers0