Css – How to put class inside Html.Dropdownlist

asp.net-mvc-4cssdrop-down-menu

I have this bizarre question, but it is bothering me a lot. I have this css class:

class="form-control"

And I need to use it in my DropDown:

@Html.DropDownList("destination", ((SelectList)ViewBag.DropList).Select(t => new SelectListItem() { Text = t.Text, Value = t.Text, Selected = (t.Text == ViewBag.Destination)}), (SelectList)ViewBag.DropList)

Best Solution

It seems you are trying to set the SelectedValue of a SelectList within the DropDownList helper which is not possible.

You have to set the SelectedValue property when you create the SelectList. See following example.

ViewBag.DropList = new SelectList(new[]{
    new SelectListItem{ Text="one", Value="1"},
    new SelectListItem{ Text="two", Value="2"},
    new SelectListItem{ Text="three", Value="3"}
    }, "Value", "Text", 2);

In the above code, I have set 2 as selected item when the SelectList is initialized. After that you can pass the SelectList and HTML attributes as below.

@Html.DropDownList("destination", (SelectList)ViewBag.DropList, new { @class = "form-control" })

Thanks!

Solution:

@Html.DropDownList("destination", ((SelectList)ViewBag.DropList).Select(t => new SelectListItem() {Text = t.Text, Value = t.Text, Selected = (t.Text == ViewBag.Destination)}), new{@class="form-control"})