我有这个奇怪的问题,但它困扰了我很多.我有这个css类: class="form-control" 我需要在我的DropDown中使用它: @Html.DropDownList("destination", ((SelectList)ViewBag.DropList).Select(t = new SelectListItem() { Tex
class="form-control"
我需要在我的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)您似乎正在尝试在DropDownList帮助程序中设置SelectList的SelectedValue,这是不可能的.
您必须在创建SelectList时设置SelectedValue属性.请参阅以下示例.
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);
在上面的代码中,我在初始化SelectList时将2设置为所选项.之后,您可以传递SelectList和HTML属性,如下所示.
@Html.DropDownList("destination", (SelectList)ViewBag.DropList, new { @class = "form-control" })
谢谢!
解:
@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"})