问题
I have this in my Controller:
ViewBag.ClientID = new SelectList(db.Clients, "ID", "Name");
This in my View (using razor)
@Html.DropDownList("ClientID", null, htmlAttributes: new { @class = "form-control",})
When I load my view I have the first client selected by default and I want to have "--Select Client--"
回答1:
you can use this overload of Html.DropDownList() to add option label:
@Html.DropDownList("ClientID",
null,
"Select Client",
htmlAttributes: new { @class = "form-control"})
if you want to set SelectedValue from database then set it in SelectList()
constructor as @Nadeem Khan posted.
回答2:
You can do it in the following manner.Please look at the below mentioned answer
ViewBag.ClientID = new SelectList(db.Clients, "ID", "--Select Client--", selectedValue);
Let me know if it helped you. Thanks
回答3:
Try this in your view:-
@Html.DropDownList("ClientID",null,"--Select Client--", htmlAttributes: new { @class = "form-control",})
You need to use this overloaded version of DropDownList.
来源:https://stackoverflow.com/questions/26777478/selectlist-selected-default-value