【问题标题】:Select List from Dictionary giving error从字典中选择列表给出错误
【发布时间】:2018-05-13 05:55:46
【问题描述】:

我如下创建了一个viewbag

Dictionary<string, long> actlist = new Dictionary<string, long>();

foreach()
{
 //filling the dictionary
}

 ViewBag.act_type = new SelectList(actlist, "Value", "Key");

在视图中调用视图包如下

@Html.DropDownList("acttype", new SelectList(ViewBag.act_type, "Value","Key"))

报错如下

SelectList 不包含名为“Key”的属性

我在这里缺少什么?

【问题讨论】:

  • 它必须是@Html.DropDownList("acttype", new SelectList(ViewBag.act_type, "Value","Text")),但它已经是SelectList,因此再次将其转换为SelectList 是毫无意义的额外开销。
  • @StephenMuecke,谢谢..整理一下@Html.DropDownList("acttype", (SelectList)(ViewBag.act_type))
  • 太棒了。现在从初学者开始,开始使用视图模型(它将包含一个属性IEnumerable&lt;SelectListItem&gt; ActTypeOptions 所以它的@Html.DropDownList("acttype", Model.ActTypeOptions) - What is ViewModel in MVC?
  • @StephenMuecke 谢谢..实现了相同的:)

标签: asp.net-mvc viewbag selectlist


【解决方案1】:

您正在创建 SelectList 两次。设置下拉列表时,传递您已经创建的 SelectList。

将字典添加到 ViewBag

ViewBag.act_type = actlist;

然后创建 SelectList

@Html.DropDownList("acttype", new SelectList(ViewBag.act_type, "Value","Key"))

您正在尝试从第一个创建一个新的 SelectList。

【讨论】:

  • 'System.Web.Mvc.HtmlHelper&lt;&gt;' has no applicable method named 'DropDownList' but appears to have an extension method by that name. Extension methods cannot be dynamically dispatched
  • 我得到了答案..你的第一个代码略有变化@Html.DropDownList("acttype", (SelectList)(ViewBag.act_type))
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多