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

后端 未结 10 457
眼角桃花
眼角桃花 2021-01-01 23:13

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         


        
相关标签:
10条回答
  • 2021-01-01 23:54

    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;" } )
    
    0 讨论(0)
  • 2021-01-01 23:55

    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:

    0 讨论(0)
  • 2021-01-01 23:56
    @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/

    0 讨论(0)
  • 2021-01-01 23:57

    Maybe if you want, try this:

    @Html.DropDownList("country",null,"-SELECT-",new { @class="chzn-select",@style="width:160px;" })
    
    0 讨论(0)
提交回复
热议问题