views:

415

answers:

3

I have a need to add custom HTML attributes, specifically classes or styles to option tags in the selects generated by Html.DropDownFor().

I've been playing with it, and for the life of me I can't figure out what I need to do to get what I need working.

Assuming I have a list of colors that I'm generating the dropdown for, where the option value is the color's identifier, and the text is the name... here's what I'd like to be able to see as output:

<select name="Color">
   <option value="1" style="background:#ff0000">Red</option>
   <option value="2" style="background:#00ff00">Green</option>
   <option value="3" style="background:#0000ff">Blue</option>
   <!-- more here -->
   <option value="25" style="background:#f00f00">Foo Foo</option>
</select

>

+2  A: 

I don't think you can do this with the built in DropDownFor helper. You probably should make your own SelectListItem class and helper to go along with it. You might find this similar request helpful.

Jab
A: 

I ended up creating my own shared Editor template.

basically I created an .ascx under the /Views/Shared/Editors folder called "ColorSelect.ascx"

Then inside that .ascx I added the following:

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<System.Int64>" %>
<%var colors = ViewData["Colors"] as ColorTable;
  var name = Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldName(String.Empty);
  var id = Html.ViewContext.ViewData.TemplateInfo.GetFullHtmlFieldId(String.Empty);
%>
  <select name="<%=name %>" id="<%=id %>">
  <%foreach(var color in colors) {%>
    <option value="<%=color.Id %>" style="background:<%=color.Hex%>;"<%if(color.Id == Model) { %> selected="selected"<%} %>><%:color.Name %></option>
  <%} %>  
  </select>

in my View (.aspx), I did this:

<%=Html.EditorFor(x => x.ColorId, "ColorSelect", new { Colors = Model.ColorTable })%>

I hope this helps anyone else that runs into the same issue I had.

blesh
A: 

Thank you! It's very easy so i can't think at the moment, so you are the first thinking. It's a experience for me

dctamtn