Shane LeBlanc
Shane LeBlanc

Reputation: 2633

@Html.DropDownListFor How to add option?

@Html.DropDownListFor(model => model.ZipFile, new SelectList(ViewBag.ZipFiles))

The above code creates me a select list just fine. But I want to make the selection optional. Unfortunately there is no empty option and I'd like to add one in. How would I do this?

Upvotes: 22

Views: 31306

Answers (3)

user5093080
user5093080

Reputation: 111

@Html.DropDownListFor(model => model.Country, new List<SelectListItem>
   {
     new SelectListItem { Text = "India", Value = "1"},
     new SelectListItem { Text = "USA", Value = "2"},
     new SelectListItem { Text = "Sreelanka", Value = "3"},
     new SelectListItem {Text  = "Africa",Value="4"},
     new SelectListItem { Text = "China", Value = "5" },
     new SelectListItem { Text = "Austraila", Value = "6" },
     new SelectListItem { Text = "UK", Value = "7" }
  }, "Select Country", 
  new {@Style = "Width:500px;height:40px;",
  @class = "form-control input-lg"})

Upvotes: 11

Darin Dimitrov
Darin Dimitrov

Reputation: 1038730

By using the proper DropDownListFor overload:

@Html.DropDownListFor(
    model => model.ZipFile, 
    new SelectList(ViewBag.ZipFiles),
    "-- please select a zip file --"
)

Upvotes: 49

Giscard Biamby
Giscard Biamby

Reputation: 4609

In the controller, when you set ViewBag.ZipFiles, add a SelectListItem to that collection.

Upvotes: 1

Related Questions