asp.net mvc How to add placeholder for html.dropdo

2020-02-28 03:20发布

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

10条回答
做个烂人
2楼-- · 2020-02-28 04:05
@Html.DropDownListFor(m => m.SelectedProductIDs, 
Model.AvaliableProducts.ToSelectList("ID","Name"),
                       new { @class = "chzn-select", 
                            data_placeholder="Please select a product" })...

Please see in more details : http://code.stylenet.ca/mvc3-data-placeholder-html5-attribute/

查看更多
老娘就宠你
3楼-- · 2020-02-28 04:10

Best way

@Html.DropDownListFor(m => m.SelectedProductIDs,
                      Model.AvaliableProducts.ToSelectList("ID","Name"),
                      "Please select a product",
                      new { @class = "chzn-select"})
查看更多
霸刀☆藐视天下
4楼-- · 2020-02-28 04:13

@Html.DropDownList("MetadataId", (MultiSelectList)ViewData["category"], "All Categories", new { @class = "chk_dropdown d-none", @id = "categories",multiple = "multiple" })

查看更多
闹够了就滚
5楼-- · 2020-02-28 04:20

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:

enter image description here

查看更多
登录 后发表回答