views:

18

answers:

1

i have an asp.net mvc page and i want to have a dropdown list with different background color like this page

i have the following code to display a dropdown list

<label>Data Source: </label><% = Html.DropDownList("DataSource", Model.CalendarDataSources, new { @id = "calendarDSDropdown", @class = "calendarDSDropdown" })%>

in my viewmodel i have:

    public IEnumerable<SelectListItem> CalendarDataSources;

which i am populating on the server. I want to add a different backlog to each SelectListItem but i can't see how to do that as select list item only has Name, Id, Selected properties

is this possible

+1  A: 

Unfortunately the built-in DropDownList helper doesn't allow you to set the style attribute on the generated option tags. You will have to roll your own helper to achieve this.

As an alternative you could use jQuery to set the color:

$(function() {
    $('select#DataSource option').each(function() {
        var option = $(this);
        option.css(
            'background-color', 
            someFunctionThatMapsTheOptionValueToAColor(option.val())
        );
    });
});
Darin Dimitrov
@Darin Dimitrov - the issue with that is that i want a different color for each item (which i know on the server)
ooo
Yes but you also know on the server the value for each item. So you could generate dynamically a mapping function between the value and the color which you could use in my jQuery example. If not you will have to implement your own html helper.
Darin Dimitrov
@Darin Dimitrov - true, i think the custom helper seems a little more straight forward but thanks for both suggestions
ooo