views:

870

answers:

2

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" })%>

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.

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

+1  A: 

Looking at the MVC source code, DropDownListFor uses DropDownList, which uses SelectInternal, which uses ListItemToOption, which wraps calls to TagBuilder. You could modify and include this source to accept extra calls to TagBuilder when the actual option tag is built.

gWiz
Yes, this is what I ended up doing... basically ripping out a bunch of code from .NET Reflector. Seems to work, but makes me kinda nervous because of all the other crap these methods seem to be doing, which can get kinda hard to decipher. I guess we'll just fix it as it goes.
No need to use Reflector; the code for ASP.NET MVC is publicly available: http://aspnet.codeplex.com/Release/ProjectReleases.aspx?ReleaseId=24471
gWiz
+1  A: 

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\"")
%>
gWiz
This **would** be the easiest, but the problem arises when I need a different value for the title attribute for every option. Then it becomes a nightmare of string manipulation.