ASP.NET MVC dropdown with a default empty option
Asked Answered
S

4

82

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

Santiagosantillan answered 3/2, 2009 at 4:23 Comment(0)
B
132

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

Bertsche answered 3/2, 2009 at 4:39 Comment(4)
Thanks. The parameter name of optionLabel for the default option threw me off :)Santiagosantillan
Geez... me too I was starting to write my own helper method... rubbish name IMHO - sounds like it would output a <label> tag next to it.Misanthrope
Be aware that the ViewData-key must be different from the DropDown-Id (in this example "Menu" != "MenuID"). Else the framework overwrites the dropdown, ignoring the third parameter.Hemihydrate
Awesome! Fixed my problem with select2.js too.Utta
B
9

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

Bacteroid answered 1/2, 2016 at 17:0 Comment(0)
O
1

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.

Oxbow answered 16/6, 2014 at 22:19 Comment(0)
S
-8

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.

Sabadell answered 1/2, 2013 at 21:39 Comment(1)
-1 This is for ASP.NET Web Forms, not MVC.Maples

© 2022 - 2024 — McMap. All rights reserved.