" that has a key I have a model: public class Auc...">

MVC 4 DropDownListFor error - there is no ViewData element of type "IEnumerable <SelectListItem>" that has a key

I have a model:

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

And the controller:

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

In the view, I have the following lines:

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

Error trying to save form:

There is no ViewData element of type "IEnumerable" that has a 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 occurred in the code.

Exception Details: System.InvalidOperationException: none ViewData element of type "IEnumerable" that has the key 'Category'.

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

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

+6
source share
2 answers

Error when I try to save the form

That is where your problem is. I suspect that you did not reassemble your list in the post method. The following lines of code that you have in the get method should also be in the post method, especially if you return the same view or view that uses the ViewBag.categoryList in the drop-down list.

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

You get this error when using a null object using dropdownlist for the html helper. This error can be easily reproduced if you do something like

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

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

-1
source

Source: https://habr.com/ru/post/944419/


All Articles