从这里读:
ASP.NET MVC
操作SelectCategory已在控制器内创建 –
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(); }
我无法理解以下行中数据的绑定.
@Html.DropDownList("MovieType")
虽然以类似的方式绑定数据,
@Html.DropDownList("IdList");
我得到以下错误 –
There is no ViewData item of type ‘IEnumerable’ that
has the key ‘IdList’.
控制器动作:
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(); }
我错过了什么?谢谢您的帮助 !
解决方法
您已设置ViewBag.MovieType =>当您使用@ Html.DropDownList(“MovieType”)时,下拉列表将使用此值.当您编写@ Html.DropDownList(“IdList”)时,帮助程序在ViewBag中找不到相应的IdList属性并抛出错误,因为它不知道从何处绑定数据.
@Html.DropDownList("SelectedMovieType",(IEnumerable<SelectListItem>)ViewBag.MovieType)
并且您的POST操作将具有SelectedMovieType参数以检索所选值.
但我会避免使用ViewBag.定义视图模型更好:
public class Myviewmodel { public string SelectedMovieType { get; set; } public IEnumerable<SelectListItem> MovieTypes { get; set; } }
然后让控制器操作填充此视图模型并将其传递给视图:
public ActionResult SelectId() { List<SelectListItem> items = new List<SelectListItem>(); items.Add(new SelectListItem { Text = "MyId1",Selected=true }); items.Add(new SelectListItem { Text = "MyId2",Value = "MyId2" }); var model = new Myviewmodel { MovieTypes = items }; return View(model); }
并在您的强类型视图中:
@model Myviewmodel @Html.DropDownListFor(x => x.SelectedMovieType,Model.MovieTypes)