SelectList selected default value

一曲冷凌霜 提交于 2019-12-14 03:16:18

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!