如何将类放入Html.Dropdownlist中?

Dan*_*iKR 3 css asp.net-mvc-4 drop-down-menu

我有这个奇怪的问题,但它困扰了我很多.我有这个css类:

class="form-control"
Run Code Online (Sandbox Code Playgroud)

我需要在我的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)
Run Code Online (Sandbox Code Playgroud)

Sar*_*nga 6

看来你正试图在助手中设置SelectedValue一个不可能SelectListDropDownList帮助.

您必须SelectedValue在创建时设置属性SelectList.请参阅以下示例.

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);
Run Code Online (Sandbox Code Playgroud)

在上面的代码中,我在SelectList初始化时将2设置为所选项.之后,您可以传递SelectList和HTML属性,如下所示.

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

谢谢!

解:

@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"})
Run Code Online (Sandbox Code Playgroud)