Alexandra Orlov
Alexandra Orlov

Reputation: 293

MVC 4 DropDownListFor error - There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key

I have a model:

public class Auction
{
    public string Title { get; set; }
    public string category { get; set; }
}

And a controller:

[HttpGet]
public ActionResult UserForm()
{

    var categoryList = new SelectList(new[] { "auto", "elec", "games", "Home" });
    ViewBag.categoryList = categoryList;
    return View();

}

In the View I have these lines:

<div class="editor-field">
    @Html.DropDownListFor(model =>
        model.category,(SelectList)ViewBag.categoryList)
    @Html.ValidationMessageFor(model => model.category)

</div>

The error I get when I try to save the form is:

There is no ViewData item of type 'IEnumerable' that has the key 'category'. Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: There is no ViewData item of type 'IEnumerable' that has the key 'category'.

I dont understand what is the problem, since I did (or tried to do) everything that is done in this guide: https://www.youtube.com/watch?v=7HM6kDBj0vE

The video can also be found in this link (Chapter 6 - Automatically binding to data in the request): http://www.lynda.com/ASPNET-tutorials/ASPNET-MVC-4-Essential-Training/109762-2.html

Upvotes: 7

Views: 14330

Answers (2)

Nawroz Salehi
Nawroz Salehi

Reputation: 79

I had the same problem,I guess when you are going to create ViewData from the same table data in the Same controller with different name it generates such error,I just copied my old ViewData from old function(method) to the new function(method) in the same controller and that worked for me.

Upvotes: -1

von v.
von v.

Reputation: 17108

The error i get when i try to save the form

That's where your problem lies. I suspect that you did not rebuild your list in your post method. The following lines of code that you have in your get method should also be in your post method especially if you are returning the same view, or a view that uses ViewBag.categoryList in a dropdownlist.

var categoryList = new SelectList(new[] { "auto", "elec", "games", "Home" });
ViewBag.categoryList = categoryList;

You get that kind of error when you use a null object with the dropdownlistfor html helper. That error can easily be reproduced if you do something like

@Html.DropDownListFor(model => model.PropertyName,null)
// or
@Html.DropDownList("dropdownX", null, "")

Upvotes: 14

Related Questions