how do i put backcolor on a selectListItem
-
26-09-2019 - |
Question
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
Solution
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())
);
});
});
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow