C # MVC Dropdownlist - no ViewData item of type 'IEnumerable <SelectListItem>' which has a key '
I was just trying to extend the previous project by adding a DropDownList to home / contact.cshtml.
My problem: I keep getting the following error when loading the page in firefox
Error: An exception of type "System.InvalidOperationException" occurred in System.Web.Mvc.dll but was not handled in user code No ViewData element of type "IEnumerable" that has key "displayGraph"
I have a different dropdown on a different page that works fine (same method), if I copy the same code into a new project, it works fine, can anyone tell me what might be causing this?
contact.cshtml - code snippet
@using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>
Filter By: @Html.DropDownList("displayGraph","Select a Graph")
<input type="submit" value="Filter" />
</p>
}
HomeController - code snippet
public ActionResult Index()
{
string chart1 = "Num Each Model Processed", chart2 = "Another chart to be assigned";
var GraphLst = new List<string> { chart1, chart1 };
ViewBag.displayGraph = new SelectList(GraphLst);
string userName = User.Identity.Name;
return View();
}
Graphdropdownmodel - code snippet
namespace TestSolution.Models
{
public class GraphDropdownModel
{
public IEnumerable<SelectListItem> Graph{ get; set; }
}
public class GraphDBContext : DbContext
{
public DbSet<GraphDropdownModel> Graphs { get; set; }
}
}
source to share
The problem is what ViewBag
is a dynamic property and DropDownList
cannot figure out that it must pass the actual type (which is SelectList
) in IEnuerable<SelectListItem>
for the conversion operator to work.
However, this is probably a good thing, because even if you actually make money, you will run into trouble. As soon as you try to send data back to the server, the MVC model binder will get confused because now you have an element in ModelState
under the name displayGraph
that is of type SelectList
and you are also sending a string value with the name displayGraph
.
This is why using is DropDownListFor()
better (or at least using an overload DropDownList()
that takes a separate property name and a collection list).
Always specify your selected property different from the one you use to populate the dropdown, it will save you a lot of headaches.
source to share