@Html.DropDownListFor; How to set different background color for each item in DDL?

Nirman picture Nirman · Jan 5, 2013 · Viewed 9.3k times · Source

I have a dropdown list (@html.DropDownListFor) wherein I am showing name of colors... I want to display each item having seperate background color.. Like, an item "Green" should be in green background, and "Yellow" in yellow background.

How can I achieve this?

Answer

viperguynaz picture viperguynaz · Jan 5, 2013

Don't forget that you can always write old fashioned HTML in a view (OMG!).

But, if you are using the code in multiple places, then write a helper that extends DropDownListFor to create your select with styling. If you are using it once, you can simply write something like:

<select>
    @foreach (var item in Model.Items)
    {
        <option style="background-color: @item.Color;" value="@item.Value">@item.Text</option>
    }
</select>