Multi select dropdown list using JQuery Plug-in Chosen

In one of my project there was a requirement to use multi select dropdown list box in MVC application.

There is a nice JQuery plug-in that provides such custom dropdown list binding with various configuration options.

Below are the reference links with samples to use JQuery chosen plug-in. The required files can also be downloaded from below links.

https://github.com/harvesthq/chosen

It is also possible to include the plug-in in MVC application using Nuget Package manager in Visual studio solution.

Include all required files into your project as per below sample image.

In Model, define two properties for the choosen dropdown box, as in below code snippet.

public class IndexModel
  {
       public string[] SelectedTeamIds { get; set; }
       public MultiSelectList TeamList { get; set; }
   }

Where ‘TeamList’ is master list of Teams which is of type MultiSelectList, and property ‘SelectedTeamIds’ contains, if there are values already in database for the dropdown list, which is a comma separated list of TeamIds.

Now, from controller action method, pass the model to the view, the model contains master list of Teams. If action method is for edit view, then it will also contain list of selected ids which are fetched from db, so that those items are rendered as selected in the dropdown list.

On the view, add reference of required .Js and .css files as below:

<link href="~/Content/choosen/css/chosen.css" rel="stylesheet" />
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Content/choosen/js/chosen.jquery.js"></script>

And bind the drop down list as below code snippet:

@Html.ListBoxFor(model => model.SelectedTeamIds, Model.TeamList, new 

{ id = "listTeams", @class = "chzn-select", data_placeholder = "Select Teams",  @style = "width:200px;" })

Also specify required configurations inside script tag:

var config = {
        '.chzn-select': {},
        '.chzn-select-width': { width: "95%" }
    }
    for (var selector in config) {
        $(selector).chosen(config[selector]);
    }

 

 

 

 

 

Leave a reply