Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

How to implement chosen plugin for MVC 3 ?

for this type of output

enter image description here

like image 728
MSTdev Avatar asked Aug 06 '13 09:08

MSTdev


People also ask

How to select multiple values from dropdown in ASP net MVC?

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.

What is jQuery chosen?

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.


1 Answers

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

like image 194
user3174077 Avatar answered Oct 21 '22 21:10

user3174077