How to implement multiple select in MVC 3 using 'chosen.js' plugin

MSTdev picture MSTdev · Aug 6, 2013 · Viewed 15.9k times · Source

How to implement chosen plugin for MVC 3 ?

for this type of output

enter image description here

Answer

user3174077 picture user3174077 · Jan 8, 2014

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