【问题标题】:ASP.NET MVC: putting custom attributes into option tag in select listASP.NET MVC:将自定义属性放入选择列表中的选项标记中
【发布时间】:2013-02-26 04:38:55
【问题描述】:

我正在使用 ASP.NET MVC,并尝试使用 HtmlHelper.DropDownListFor 方法呈现选择列表,如下所示:

<%= Html.DropDownListFor(x => x.AllTopics, SelectListHelper.GetSelectListItems(Model.AllTopics), "Select a Topic", new { id = "allTopics", @class = "topic-dropdown" })%>

其中 SelectListHelper 只是从我们传入的任何集合中返回一个IList&lt;SelectListItem&gt;。这对于简单的事情很好,但我希望能够为每个 option 标签添加一个标题属性( 不是 选择 列表本身)。但是 DropDownListFor 只接受一个IEnumerable&lt;SelectListItem&gt;,而 SelectListItem 没有任何可以放入 title 属性的地方。

有什么方法可以做到这一点,而不需要前面的 DropDownListFor 方法并手动写出选择列表和每个元素?

【问题讨论】:

    标签: asp.net asp.net-mvc drop-down-menu


    【解决方案1】:

    DropDownList 及其衍生产品不支持您正在寻找的功能。但是您也可以简单地处理 DropDownList 返回的字符串。

    <%= 
      Html.DropDownListFor(x => x.AllTopics,
        SelectListHelper.GetSelectListItems(Model.AllTopics),
        "Select a Topic", 
        new { id = "allTopics", @class = "topic-dropdown" })
      .Replace("<option", "<option attr=\"value\"")
    %>
    

    【讨论】:

    • would 是最简单的,但是当我需要为每个选项的 title 属性设置不同的值时,就会出现问题。然后它变成了字符串操作的噩梦。
    【解决方案2】:

    查看MVC源代码,DropDownListFor使用DropDownList,它使用SelectInternal,它使用ListItemToOption,它包装了对TagBuilder的调用。您可以修改并包含此源以在构建实际选项标签时接受对 TagBuilder 的额外调用。

    【讨论】:

    • 是的,这就是我最终要做的……基本上是从 .NET Reflector 中提取出一堆代码。似乎有效,但让我有点紧张,因为这些方法似乎正在做的所有其他废话,这可能有点难以破译。我想我们会及时修复它。
    • 无需使用Reflector; ASP.NET MVC 的代码是公开的:aspnet.codeplex.com/Release/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-11-21
    • 2013-11-23
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 1970-01-01
    • 2010-10-11
    相关资源
    最近更新 更多