ASP.NET MVC:将自定义属性放入选择列表中的选项标签 [英] ASP.NET MVC: putting custom attributes into option tag in select list

查看:10
本文介绍了ASP.NET MVC:将自定义属性放入选择列表中的选项标签的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using ASP.NET MVC, and am trying to render a select list with the HtmlHelper.DropDownListFor method, like so:

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

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

where SelectListHelper just returns an IList<SelectListItem> from whatever collection we're passing in. This works fine for simple things, but I want to be able to add a title attribute to each option tag (not the select list itself). But the DropDownListFor only takes in an IEnumerable<SelectListItem>, and the SelectListItem does not have anyplace that I can put in the title attribute.

有没有什么办法可以在不放弃 DropDownListFor 方法并手动写出选择列表和每个元素的情况下做到这一点?

Is there any way to do this without foregoing the DropDownListFor method and writing out the select list and each element by hand?

推荐答案

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

DropDownList and derivatives don't support the functionality you're looking for. But you could also simply process the string returned by DropDownList.

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

这篇关于ASP.NET MVC:将自定义属性放入选择列表中的选项标签的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆