Warm tip: This article is reproduced from serverfault.com, please click

How to add css class dyanmically to Select List Item in DropDownList Razor

发布于 2020-12-02 11:31:07

Hie, I want to add a CSS class to a particular SelectListIem in DropDowList in MVC Razor syntax.

I actually want to implement a CSS for:

new SelectListItem{ Text="Out Of 5", Value = "Out Of 5"},

instead of implementing for the entire control.

Below is the code snippet:

@Html.DropDownList("Options", new List<SelectListItem>
{
   new SelectListItem{ Text="Select Options", Value = "1" },
   new SelectListItem{ Text="CheckBox", Value = "1" },
   new SelectListItem{ Text="Radio", Value = "2" },
   new SelectListItem{ Text="Rating", Value = "3"},
   new SelectListItem{ Text="Out Of 5", Value = "Out Of 5"},
   new SelectListItem{ Text="Out Of 10", Value = "Out Of 10"},
   new SelectListItem{ Text="Text", Value = "4"},
}, new { @class = "form-control input-group, dropdown-submenu" })







                            
    
                           
Questioner
Dhruvi Parikh
Viewed
0
Yiyi You 2020-12-03 09:51:01

Here are two solutions:

First one(foreach options of dropdown,and if text="Out Of 5",add class to it):

@Html.DropDownList("Options", new List<SelectListItem>
{
   new SelectListItem{ Text="Select Options", Value = "1" },
   new SelectListItem{ Text="CheckBox", Value = "1" },
   new SelectListItem{ Text="Radio", Value = "2" },
   new SelectListItem{ Text="Rating", Value = "3"},
   new SelectListItem{ Text="Out Of 5", Value = "Out Of 5"},
   new SelectListItem{ Text="Out Of 10", Value = "Out Of 10"},
   new SelectListItem{ Text="Text", Value = "4"},
}, new { @class = "form-control input-group, dropdown-submenu",@id="select" })
<script>
    $(function () {
        $("#select > option").each(function () {
            if (this.text == "Out Of 5") {
                $(this).addClass("special");
            }
        });
    })
</script>
<style>
    .special {
        color:red;
    }
</style>

2.Second one(change selectlistItem to ,and add class to <option value="Out Of 5" class="special">Out Of 5</option>):

<select class="form-control input-group, dropdown-submenu">
    <option value="1">Select Options</option>
    <option value="1">CheckBox</option>
    <option value="2">Radio</option>
    <option value="3">Rating</option>
    <option value="Out Of 5" class="special">Out Of 5</option>
    <option value="Out Of 10">Out Of 10</option>
    <option value="4">Text</option>
<style>
    .special {
        color:red;
    }
</style>

result: enter image description here