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
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, "")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With