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

后端 未结 4 662
一生所求
一生所求 2021-02-04 18:34

How to implement chosen plugin for MVC 3 ?

for this type of output

\"enter

4条回答
  •  情书的邮戳
    2021-02-04 19:13

    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

提交回复
热议问题