Reading from here: ASP.NET MVC
Action SelectCategory has been created inside controller –
public ActionResult SelectCategory() {
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "Action", Value = "0"});
items.Add(new SelectListItem { Text = "Drama", Value = "1" });
items.Add(new SelectListItem { Text = "Comedy", Value = "2", Selected = true });
ViewBag.MovieType = items;
return View();
}
I am not able to understand binding of Data in following line.
@Html.DropDownList("MovieType")
While binding data in similar way,
@Html.DropDownList("IdList");
I obtain following error-
There is no ViewData item of type ‘IEnumerable’ that
has the key ‘IdList’.
Controller Action:
public ActionResult SelectId()
{
List<SelectListItem> items = new List<SelectListItem>();
items.Add(new SelectListItem { Text = "MyId1", Value = "MyId1", Selected=true });
items.Add(new SelectListItem { Text = "MyId2", Value = "MyId2" });
ViewBag.IdList = items;
return View();
}
What am I missing ? Thank you for your help !
You have set
ViewBag.MovieType=> when you use@Html.DropDownList("MovieType")the dropdown will use this value. When you write@Html.DropDownList("IdList"), the helper doesn’t find a correspondingIdListproperty in ViewBag and throws an error because it doesn’t know from where to bind the data.Alternatively if you want to change the name of the dropdown you could use the following:
and your POST action will have a
SelectedMovieTypeparameter to retrieve the selected value.But I would avoid ViewBag. Defining a view model is better:
and then have your controller action populate this view model and pass it to the view:
and in your strongly typed view: