Asp.net Mvc How To Add Placeholder For Html.dropdownlist
Answer :
You could try this:
@Html.DropDownList("country", new SelectList(ViewBag.countries), "-select- ", new { @class="chzn-select", @style="width:160px;" })  In your collection ViewBag.Countries just insert a dummy record at the from of the collection with the name "-select-". You should be able to force the selected item with an alternate constructor like this:
@Html.DropDownList("country",      new SelectList(ViewBag.countries as System.Collections.IEnumerable,      "name", "name", "-select-"), new { @class="chzn-select", @style="width:160px;" } )  A quick and (not so) dirty solution involving jQuery.
Instead of adding a dummy item at the start of the list, prepend a new option that is disabled. The main advantage is that you don't have to mess with a dummy item in your list, and most important, you won't be able to select that dummy item in the page:
@Html.DropDownList("yourName", yourSelectList, new { @class = "form-control select-add-placeholder" })   Then somewhere after:
$(".select-add-placeholder").prepend("<option value='' disabled selected>Select an option...</option>");   Which looks like:

Comments
Post a Comment