ASP.NET MVC dropdown with a default empty option

asp.net Mvchtml.dropdownlistforHtml Select

asp.net Mvc Problem Overview


Is there a way to include a default empty option (or with text) if there is no selected value for a dropdownlist?

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

The below will prepend string.Empty to the SelectList (or IEnumerable) specified in the ViewData["Menu"] item. The select will have id and name MenuID.

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

Documentation: DropDownList method

Solution 2 - asp.net Mvc

For 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 :

inline image

Solution 3 - asp.net Mvc

This easy solution worked for my mvc5 project:

in view:

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

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

Solution 4 - asp.net Mvc

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 an asp:ListItem in the DropDownList and that will become your default item with all the databound items coming after it.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJames Newton-KingView Question on Stackoverflow
Solution 1 - asp.net MvctvanfossonView Answer on Stackoverflow
Solution 2 - asp.net MvctiepnvView Answer on Stackoverflow
Solution 3 - asp.net MvcPixelPlexView Answer on Stackoverflow
Solution 4 - asp.net MvccjbarthView Answer on Stackoverflow