I'm using asp.net mvc 3.
I have this dropdownlist of countries and I want to add a placeholder for it. Here's my code:
@Html.DropDownList("country",
new SelectList(ViewBag.countries as System.Collections.IEnumerable,
"name", "name"), new { @class="chzn-select", @placeholder="-select-",
@style="width:160px;" } )
But the placeholder doesn't work, while the style works.
How do I set a placeholder for this?
PS. I just want to use @Html.DropDownList
, not @Html.DropDownListFor
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:
Try this
Or
I can see that there is not an easy answer. I´ve developed a simple solution but it gives some work. This will work for DropDownList and DropDownListFor
First create an Extension Class where ever you want. (Must be Static with static methods) And Then add the following extension method
Now Note the this Extension only add a new attribute, the disableLabel This will check if you want to disable or not the label.
Now You let´s go to view´s side first declare that you want to use the extension class you have created ex:
@using WF.Infrastructure.Extension;
Now you use like it:
@Html.DropDownList("Unidade", lstUnidade, "Text of Option Disabled",true)
Note: if you want it to work with DropDownListFor, just add another extension method for your Extension Class with this signature:
public static MvcHtmlString DropDownListFor<TModel, TProperty>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, TProperty>> expression, IEnumerable<SelectListItem> selectList, string optionLabel,bool disableLabel)
PS: If you declare your extension methods in a separated project like me, you will need to add assemblies ( System.Web.Mvc, System.Web) and in your Extension Class you will need to declare:
You could try this:
Maybe if you want, try this: