【问题标题】:Bind DropdownlistFor with the Viewbag将 DropdownlistFor 与 Viewbag 绑定
【发布时间】:2013-12-13 10:08:51
【问题描述】:

我正在尝试将 DropDownListFor 助手与控制器中定义的 viewbag 绑定。但我收到错误。

查看代码:-

@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as SelectListItem)) 

控制器代码:-

 public ActionResult Create()
>  {
>    var content = from p in db.Currency
>                  where p.IsActive == true
>                  orderby p.CurrencyName
>                  select new { p.CurrencyID, p.CurrencyCode };
> 
>    var x = content.ToList().Select(c => new SelectListItem         
>                            {
>                               Text = c.CurrencyCode,
>                               Value = c.CurrencyID.ToString(),
>                               Selected = (c.CurrencyID == 68)
>                            }).ToList();
>             ViewBag.CurrencyList = x;
> 
>             return View();            
>         }

收到错误:- System.Web.Mvc.HtmlHelper'不包含'DropDownListFor'的定义和最佳扩展方法重载'System.Web.Mvc.Html.SelectExtensions.DropDownListFor(System.Web.Mvc.HtmlHelper, System.Linq.Expressions. Expression>, System.Collections.Generic.IEnumerable)' 有一些无效参数

【问题讨论】:

  • 您不能将单个 selectListItem 分配给下拉列表。 ViewBag.CurrencyList 作为 SelectListItem,在这里您需要一个选择列表或一个列表或 Enumerable 项。所以 IEnumerable 起作用了。只要你想知道。

标签: asp.net-mvc asp.net-mvc-4


【解决方案1】:

你需要改变

@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as SelectListItem))

@Html.DropDownListFor(model => model.CurrencyID, ViewBag.CurrencyList as IEnumerable<SelectListItem>)

【讨论】:

    【解决方案2】:

    您也可以这样做。它应该工作:

    ViewBag.CurrencyID = x;
    

    在视野中:

    @Html.DropDownListFor(model => model.CurrencyID, null)
    

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      相关资源
      最近更新 更多