0
我试图使用MVC 5 +实体框架将下拉列表中的值保存到数据库。在下拉列表中的值从数据库中取出的(和显示),但是当我保存网页条目,则在OrderSourceList
的值是零和OrderSourceId
= 0 型号将下拉列表中的值保存到实体框架MVC
public class OrderFullModel
{
[Display(Name = "OrderSource")]
public IList<SelectListItem> OrderSourceList {get;set;}
public int OrderSourceId { get; set; }
}
控制器
public ActionResult Create() //this is returning the right dropdownlist
{
var orderSources = _repository.All<OrderSource>().OrderBy(m => m.NameRu).ToList();
ViewBag.MyOrderSources = new SelectList(orderSources, "Id", "NameRu", 0);
return View();
}
查看
@Html.LabelFor(m => m.OrderSourceList)
@Html.DropDownListFor(m => m.OrderSourceList, (SelectList)ViewBag.MyOrderSources)
然后我得到Message =具有'OrderSourceId'键的ViewData项的类型是'System.Int32',但必须是'IEnumerable'类型。 –
我建议你看看[这个答案](http://stackoverflow.com/a/18549424/3175307)了解它是如何融合在一起的一个例子。看起来很奇怪,你在你的模型中有一个SelectListItems列表,如果不是OrderSources的列表? –
@sidux,因为'ViewBag.MyOrderSources'为'null',你会得到这个错误,很可能是因为你没有在POST方法中重新赋值,因为ModelState无效。 –