Kaushal Kishore
Kaushal Kishore

Reputation: 130

How to add Class to SelectListItem in ASP.NET MVC5 Razor Syntax?

I created a select input field using the Razor. Given below is the code:

@Html.DropDownList("selectOption", new[] {
                        new SelectListItem()
                        {
                            Text ="Option 1" , Value = "1"
                        },
                        new SelectListItem()
                        {
                            Text = "Option 2" , Value = "2"
                        },
                        new SelectListItem()
                        {
                            Text = "Option 3" , Value = "3"
                        }
                    }, 
                    "Choose an Option...", 
                    new {@class = "form-control" })

I am aware of adding custom class to select input field but how do I add custom class to each of the select options? Is it even possible using razor syntax?

I can get the results by using jQuery but I want to know whether there exists method using only razor.

Upvotes: 2

Views: 1524

Answers (1)

musefan
musefan

Reputation: 48455

You can't do it with the built in methods. You could create your own extension method or helper, however it would be much easier to just create the control yourself using HTML:

<select class="form-control" id="selectOption" name="selectOption">
    <option value="">Choose an Option...</option>
    <option class="some-class-1" value="1">Option 1</option>
    <option class="some-class-2" value="2">Option 2</option>
    <option class="some-class-3" value="3">Option 3</option>
</select>

It even makes it more readable (in my opinion). You shouldn't feel like you have to use the helpers for everything.

Upvotes: 0

Related Questions