Domanda

I am using jQuery Chosen plugin in my ASP.NET MVC application. The data-placeholder attribute is not working when the dropdownlist has items in it. Instead of showing default text it automatically selects the first item in the list.

This is how I define my dropdownlist.

@Html.DropDownListFor(m => m.Keep, Model.Data, 
     new { @class = "chzn-select", data_placeholder = "Default..." })

If Model.Data is empty (it is filled in view model using EF), then default text is displayed. Otherwise, the first item is selected. I always want my dropdownlist to show default value.

I apply the plugin via $('.chzn-select').chosen(); Nothing special.

Any ideas ? Thanks in advance.

È stato utile?

Soluzione

You need to add an empty option first.

as per documentation - http://harvesthq.github.com/chosen/

Note: on single selects, the first element is assumed to be selected by the browser. To take advantage of the default text support, you will need to include a blank option as the first element of your select list.

Maybe use jQuery to add it

$(".chzn-select").prepend("<option></option>");

Altri suggerimenti

@Html.DropDownListFor(model => model.categoryModel.Id, ViewBag.CategoryList as SelectList, "", new { @class = "chzn_a", data_placeholder = "Choose Category.." })

add "" after your SelectList, if below code didn't work to you

$(".chzn_a").prepend("<option></option>");

I had same problem and I did the following:

when you initialise the chosen field you have to not use % at width size.

$(".chosen").chosen({
'no_results_text' :'Oops, nothing found!',
'width'           :'700px',
'search_contains' : true,
'placeholder_text_multiple':'Please choose something ...',
'display_selected_options':false             

});

Becoz your default value is replaced by your values in the list. So to show your default value, add that default value in your list as first item.

Check whether there is record binding to the first element in the list and your model

Default Text Support

Chosen automatically sets the default field text ("Choose a country...") by reading the select element's data-placeholder value. If no data-placeholder value is present, it will default to "Select an Option" or "Select Some Options" depending on whether the select is single or multiple. You can change these elements in the plugin js file as you see fit.

Note: on single selects, the first element is assumed to be selected by the browser. To take advantage of the default text support, you will need to include a blank option as the first element of your select list. See: Default Text Support

If your code even with adding blank option, not works; then you should know that some times browser need to new page to load code and take effect!

so close your tab and open new tab and go to your project page to see changes!

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top