How to implement chosen plugin for MVC 3 ?
for this type of output
The ASP.NET MVC MultiSelect Dropdown is a quick replacement for the HTML select tag for selecting multiple values. HTML MultiSelect Dropdown is a textbox control that allows the user to type or select multiple values from a list of predefined options.
Chosen is a JavaScript plugin that makes long, unwieldy select boxes much more user-friendly. It is currently available in both jQuery and Prototype flavors.
This is my code how to make chosen.js work with javascript/MVC
This is my code for my dropdown
@Html.DropDownListFor(m => m.CategoryId,
new SelectList(Model.Categories, "Id", "Name"),
"Choose a Category...",
new
{
id = "CategoryId",
multiple = "",
@class = "chzn-select srs-select search-dropdown",
data_placeholder = "Choose a Category..."
})
Here I use 'chzn-select' styling
-- In the document ready, one should have the .chosen() function called.
$(document).ready(function () {
$('.chzn-select').chosen();
});
In Javascript, to retrieve what was selected, this is the code
The code to retrieve items selected in the dropdownbox
var selectedCategoryId = $('Select#CategoryId').val();
var selectedCategories = "";
if (selectedCategoryId != null) {
$.each(selectedCategoryId, function (index, value) {
selectedCategories = selectedCategories + value + ",";
});
}
Basically selectedCategories has ID of the items selected, seperated by ','
To update the dropdown with the values selected
Copy your values into a array
var categoryArray = new Array();
... there is code that initializes the array whih the values that were selected before.
//code to make you selection, the array has your values.
$('Select#CategoryId').val(categoryArray);
$('.chzn-select').trigger('chosen:updated');
Hope this helps
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With