ASP.NET MVC output with empty default option

Is there a way to enable an empty default option (or with text) if there is no selected value for the drop-down list?

+74
asp.net-mvc html-select html.dropdownlistfor
Feb 03 '09 at 4:23
source share
4 answers

Below, string.Empty is added to the SelectList (or IEnumerable) specified in the ViewData ["Menu"] element. The selection will have the identifier and name MenuID .

 <%= Html.DropDownList( "MenuID", (IEnumerable<SelectListItem>)ViewData["Menu"], string.Empty ) %> 

Documentation: DropDownList Method

+120
Feb 03 '09 at 4:39
source share

Example:

  Controller : private void InitScreenInfoCollate() { IEnumerable<MstBrd> listbrd = ibrandRepository.GetItemsByUsercode(""); ViewBag.Brands = new SelectList(listbrd, "brd_cod", "brd_mei", null); } View : @Html.DropDownList("Brands", null, string.Empty, new { @class = "form-control"}) 

Result:

embedded image

+6
Feb 01 '16 at 17:00
source share

This lightweight solution worked for my mvc5 project:

:

 @{ Model.ModelItemsList.Add(new ModelItem{ }); SelectList modelItemSelectList = new SelectList(Model.ModelItemsList, "ModelItemID", "ModelItemName"); } 

Just add a new item to the List<> that you want to display in your view. In my case, I added an empty "ModelItem" to my List<ModelItem> ModelItemList . Since my ModelItemID is Guid, I had to check Guid.Empty in my controller method and do some code. That's all.

0
Jun 16 '14 at 22:19
source share

The solution presented here worked very well for me: http://forums.asp.net/t/1142484.aspx/1

The basic idea is that you set the AppendDataBoundItems property of your DropDownList to true , and then put asp:ListItem in the DropDownList , and this will become your default item with all the data details that appear after it.

-5
Feb 01 '13 at 21:39
source share



All Articles