-1

I have a simple select list being generated in my action method (code below)

Viewbag.Select = new SelectList(db.esp_admin_form_demographics.Where(x => x.category == (int) SelectHelper.ClientSelectOptions.Demographics.BirthCountry || x.category == 999), "id", "value", "");

How is it possible to add a placeholder value in there as the default value?

Paul Coan
  • 302
  • 1
  • 3
  • 15
  • 1
    What do you mean a _placeholder_? Are you wanting to have the first option as (say) _Please select_? –  Aug 01 '18 at 02:48
  • @StephenMuecke "Placeholder" means a value set as initial value that will shown when `SelectList` bound to a DDL or DDLF. Similar issues [here](https://stackoverflow.com/questions/16073464/asp-net-mvc-how-to-add-placeholder-for-html-dropdownlist) and [here](https://stackoverflow.com/questions/28468499/cannot-find-a-way-to-add-a-placeholder-for-an-mvc-5-dropdownlistfor/28469469). – Tetsuya Yamamoto Aug 01 '18 at 02:57
  • @TetsuyaYamamoto, Its only the initial (default) value if the property OP is binding to does not match a value of one of the options (which is why I was asking) –  Aug 01 '18 at 03:00
  • Possible duplicate of [Create DropDownListFor from SelectList with default value](https://stackoverflow.com/questions/17215558/create-dropdownlistfor-from-selectlist-with-default-value) – TAHA SULTAN TEMURI Aug 01 '18 at 04:52
  • @TAHASULTANTEMURI, I do not think that is what OP is asking, but in anycase that answer is completely wrong as explained [here](https://stackoverflow.com/questions/41719293/mvc5-how-to-set-selectedvalue-in-dropdownlistfor-html-helper/41731685#41731685) (no idea how it was accepted) –  Aug 01 '18 at 05:50

1 Answers1

1

Here is the solution to set placeholder as the default value in your SelectList/DropDownList :

In the Controller Method:

var espAdminList =  db.esp_admin_form_demographics.Where(x => x.category == (int) SelectHelper.ClientSelectOptions.Demographics.BirthCountry || x.category == 999)

Viewbag.EspAdminSelectList = new SelectList(espAdminList, "id", "value");

Then in the view:

@Html.DropDownList("EspAdminId",ViewBag.EspAdminSelectList as SelectList, "Select Esp. Admin", new { @class = "form-control" })
TanvirArjel
  • 30,049
  • 14
  • 78
  • 114