Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

c# - mvc 5 SelectList from table with blank value for DropDownList

I am using below code to create a drop down

Controller

ViewBag.Id= new SelectList(db.TableName.OrderBy(x => x.Name),"Id","Name")

View

 @Html.DropDownList("Id", null, htmlAttributes: new { @class = "form-control" })

My question is how can I Modify SelectList to add a blank item so that there is a blank item automatically added for DropDownList.

Thanks.

question from:https://stackoverflow.com/questions/35093841/mvc-5-selectlist-from-table-with-blank-value-for-dropdownlist

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use one of the overloads that accepts an optionLabel

@Html.DropDownListFor(m => m.ID, (SelectList)ViewBag.MyList, "Please select", new { @class = "form-control" })

or if you do not want to use the strongly typed methods

@Html.DropDownList("ID", (SelectList)ViewBag.MyList, "Please select", new { @class = "form-control" })

Which will add the first option with the text specified in the 3rd parameter and with a null value

<option value="">Please Select</option>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...