【问题标题】:Populate dropdown list with dictionary values using html helpers使用 html 助手使用字典值填充下拉列表
【发布时间】:2014-02-24 08:01:01
【问题描述】:

我创建了一个字典并用枚举值设置它。我想使用 Html.DropdownlistFor 填充下拉列表。这是我的行动:

 public ActionResult Index()
 {
     Dictionary<string, string> TagsDictionary = new Dictionary<string, string>();
     Enum.GetNames(typeof(System.Tags)).ToList().ForEach(x => TagsDictionary.Add(x, Resources.PageResources.ResourceManager.GetString(String.Format("Tags_{0}", x))));           
     return View(TagsDictionary);
 }

但我不知道如何编写 View 以在页面加载时获取下拉列表中的字典值

【问题讨论】:

  • 为什么要创建一个字典来填充视图中的下拉菜单?

标签: asp.net-mvc asp.net-mvc-4 razor html-helper


【解决方案1】:

使用SelectListItem:

public ActionResult Index()
{
    List<SelectListItem> tagsList = new List<SelectListItem>();
    Enum.GetNames(typeof(System.Tags)).ToList()
        .ForEach(x => tagsList .Add(new SelectListItem(){Value = x, Text = Resources.PageResources.ResourceManager.GetString(String.Format("Tags_{0}", x))}));
    return View(tagsList );
}    

在您看来,您可以调用:

@Html.DropDownList("Tags List", Model)

【讨论】:

  • 当您写入return View(yourVariableHere); 时,Razor 引擎会自动将您视图中的Model 变量的值设置为yourVariableHere。该视图没有引用控制器中的变量,但可以通过Model 访问该值。
  • 不,没必要。在您的视图中,Model_is_ tagsList。你不再需要任何东西了。
  • 使用Model。真的是一回事,只是换了个名字而已。
  • @Html.DropDownList("Tags List", Model) 无法将我的模型转换为选择列表
  • 您的视图中有@model 定义吗?
猜你喜欢
  • 2018-03-12
  • 2017-03-06
  • 2017-03-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-18
  • 2012-11-07
相关资源
最近更新 更多