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
>
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:
in my View (.aspx), I did this:
I hope this helps anyone else that runs into the same issue I had.