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

查看:826
本文介绍了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&LT; SelectListItem&GT; 无论从任何收集我们传递在这工作正常进行简单的事情,但我希望能够加入一个。 title属性给每个选项标记(不可以选择列表本身)。但DropDownListFor只需要在的IEnumerable&LT; SelectListItem方式&gt; 和SelectListItem没有任何地方,我可以把title属性

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天全站免登陆