asp.net mvc How to add placeholder for html.dropdownlist
Asked Answered
I

10

15

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

Ioneionesco answered 18/4, 2013 at 2:20 Comment(0)
D
6

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;" } )
Destiny answered 18/4, 2013 at 2:43 Comment(3)
Here's my way and it finally works. @Html.DropDownList("country", new SelectList(ViewBag.countries as System.Collections.IEnumerable, "name", "name"), "-SELECT-", new { @class="chzn-select", @placeholder="-SELECT-", @style="width:160px;" } )Ioneionesco
I think the @@placeholder is useless, though the @@style defiantly works. I'm wondering whether @placeholder is a correct keyword. I tried to search the documentation or specification of @@html.DropDownList but failed. Do you know where I can find those?Ioneionesco
You're right, the placeholder attribute is useless in the example I gave since the SelectList constructor is being passed the selected value, which should cause it to default to selected.Destiny
T
14

You could try this:

@Html.DropDownList("country", new SelectList(ViewBag.countries), "-select- ", new { @class="chzn-select", @style="width:160px;" })
Tequilater answered 20/5, 2015 at 11:31 Comment(1)
Issue is, you can select the option label.Publish
P
8

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

Publish answered 14/11, 2018 at 15:54 Comment(1)
This is quite a nice solution. User can't select the place holder option, so you don't have to worry much about validation except the scenario where nothing is changed in the form.Bryannabryansk
D
6

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;" } )
Destiny answered 18/4, 2013 at 2:43 Comment(3)
Here's my way and it finally works. @Html.DropDownList("country", new SelectList(ViewBag.countries as System.Collections.IEnumerable, "name", "name"), "-SELECT-", new { @class="chzn-select", @placeholder="-SELECT-", @style="width:160px;" } )Ioneionesco
I think the @@placeholder is useless, though the @@style defiantly works. I'm wondering whether @placeholder is a correct keyword. I tried to search the documentation or specification of @@html.DropDownList but failed. Do you know where I can find those?Ioneionesco
You're right, the placeholder attribute is useless in the example I gave since the SelectList constructor is being passed the selected value, which should cause it to default to selected.Destiny
E
4
@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/

Eldwin answered 30/7, 2014 at 15:30 Comment(1)
Referring to a link is discouraged as the integrity of the link may expire at a later date. Please explain how that code works and why in your post in order for it to be self-contained, and use the link only as a reference.Wichern
A
1

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

public static MvcHtmlString DropDownList(this HtmlHelper htmlHelper,string name, IEnumerable<SelectListItem> selectList, string optionLabel, bool disableLabel)
{
    MvcHtmlString mvc = htmlHelper.DropDownList(name, selectList, optionLabel);
    if (disableLabel)
    {
        string disabledOption = mvc.ToHtmlString();
        int index = disabledOption.IndexOf(optionLabel);
        disabledOption = disabledOption.Insert(index - 1, " disabled");

        return new MvcHtmlString(disabledOption);
    }
    else
    {
        return mvc;
    }
}

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:

using System.Web.Mvc;
using System.Web.Mvc.Html;
Avail answered 3/11, 2014 at 20:14 Comment(0)
P
0

Maybe if you want, try this:

@Html.DropDownList("country",null,"-SELECT-",new { @class="chzn-select",@style="width:160px;" })
Pinnatiped answered 8/8, 2019 at 6:56 Comment(0)
P
0

Try this:

@Html.DropDownList("MetadataId", (MultiSelectList)ViewData["category"], "All Categories",
    new { @class = "chk_dropdown d-none", @id = "categories", multiple = "multiple" })
Palaeolithic answered 4/11, 2019 at 9:32 Comment(0)
M
-1

Try this

@Html.DropDownListFor(m => m.SelectedProductIDs, Model.AvaliableProducts.ToSelectList("ID","Name"), new { @class = "chzn-select", data-placeholder="Please select a product" })

Or

@Html.DropDownListFor(model => model.SelectedItemID, new SelectList(Model.employeeList, "Value", "Text"), new Dictionary<string, object> { { "data-placeholder", "Choose a sandbox..." }, { "class", "chzn-select" }, { "style", "width:200px;" } })
Maddie answered 18/4, 2013 at 4:16 Comment(1)
Because I already have another model passed to this page so I don't want to use DropDownListFor, only use DropDownListIoneionesco
L
-1

Best way

@Html.DropDownListFor(m => m.SelectedProductIDs,
                      Model.AvaliableProducts.ToSelectList("ID","Name"),
                      "Please select a product",
                      new { @class = "chzn-select"})
Loathing answered 7/12, 2017 at 7:2 Comment(0)
L
-1
@Html.DropDownListFor(m => m.SelectedProductIDs,
                      Model.AvaliableProducts.ToSelectList("ID","Name"),
                      "Please select a product",
                      new {enter code here @class = "chzn-select"})
Loathing answered 29/5, 2018 at 12:18 Comment(1)
While this code snippet may solve the question, including an explanation really helps to improve the quality of your post. Remember that you are answering the question for readers in the future, and those people might not know the reasons for your code suggestion.Vega

© 2022 - 2024 — McMap. All rights reserved.