Search code examples
asp.net-mvcvb.netasp.net-mvc-3

Remove Blank Entry on DropDownList in MVC


I have been looking but couldn't find any way to remove the blank item on my dropdown list. Ideally, I would like to do this without altering the model. I just want to remove the blank item from the dropdown list so that users are forced to select one (so they can't select "blank").

Note: I am using the default dropdown list that comes with the MVC framework.

Here is my code:

' controller action:

ViewBag.CompanyId = New SelectList(db.Companies, "CompanyId", "Name")

' view:

@Html.DropDownList("CompanyId", String.Empty)
@Html.ValidationMessageFor(Function(model) model.CompanyId)

Solution

  • How are you building the options for your dropdown?

    I never have blank options.

    I usually create my dropdown like this:

      @Html.DropDownListFor(x=>x.Client, new SelectList(Model.Clients))
    

    Obviously your model options will be different.

    Answer: Remove String.Empty