2015-11-01 103 views
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)  

回答

2

DropDownListFor是预计,在要显示/设置列表中值的计算式的帮手,所以:

@Html.DropDownListFor(m => m.OrderSourceId, (SelectList)ViewBag.MyOrderSources) 

目前你问一个下拉菜单设置列表的价值。

Docs

public static MvcHtmlString DropDownListFor(
this HtmlHelper<TModel> htmlHelper, 
Expression<Func<TModel, TProperty>> expression, 
IEnumerable<SelectListItem> selectList) 

表达: 标识包含的属性来显示对象的表达式。

selectList: 用于填充下拉列表的SelectListItem对象的集合。

+0

然后我得到Message =具有'OrderSourceId'键的ViewData项的类型是'System.Int32',但必须是'IEnumerable '类型。 –

+0

我建议你看看[这个答案](http://stackoverflow.com/a/18549424/3175307)了解它是如何融合在一起的一个例子。看起来很奇怪,你在你的模型中有一个SelectListItems列表,如果不是OrderSources的列表? –

+0

@sidux,因为'ViewBag.MyOrderSources'为'null',你会得到这个错误,很可能是因为你没有在POST方法中重新赋值,因为ModelState无效。 –

相关问题