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 corresponding IdList
property 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:
@Html.DropDownList("SelectedMovieType", (IEnumerable<SelectListItem>)ViewBag.MovieType)
and your POST action will have a SelectedMovieType
parameter to retrieve the selected value.
But I would avoid ViewBag. Defining a view model is better:
public class MyViewModel
{
public string SelectedMovieType { get; set; }
public IEnumerable<SelectListItem> MovieTypes { get; set; }
}
and then have your controller action populate this view model and pass it to the view:
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" });
var model = new MyViewModel
{
MovieTypes = items
};
return View(model);
}
and in your strongly typed view:
@model MyViewModel
@Html.DropDownListFor(x => x.SelectedMovieType, Model.MovieTypes)
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…