我想在我的看法中填充一个下拉列表.任何帮助是极大的赞赏.谢谢.
错误:
Unable to cast the type ‘System.Int32’ to type ‘System.Object’.
LINQ to Entities only supports casting Entity Data Model primitive types.
控制器:
ViewBag.category = (from c in new IntraEntities().CategoryItems select new SelectListItem() {Text=c.Name,Value=""+c.ID }).ToList<SelectListItem>();
视图:
Category:<br />@Html.DropDownList("category",(List<SelectListItem>)ViewBag.category)
解决方法
这个怎么样:
ViewBag.category = from c in new IntraEntities().CategoryItems.ToList() select new SelectListItem { Text = c.Name,Value = c.ID.ToString() };
以及如何使用强类型视图模型,而不是ViewBag的一些弱类型的垃圾(这是我的方式)?
喜欢这个:
public class Categoryviewmodel { public string CategoryId { get; set; } public IEnumerable<SelectListItem> Categories { get; set; } }
然后:
public ActionResult Foo() { var model = new Categoryviewmodel { Categories = from c in new IntraEntities().CategoryItems.ToList() select new SelectListItem { Text = c.Name,Value = c.ID.ToString() } }; return View(model); }
最后在你的强类型视图中:
@model Categoryviewmodel @using (Html.BeginForm()) { @Html.DropDownListFor(x => x.CategoryId,Model.Categories) <button type="submit">OK</button> }
好多了,你不觉得吗