Using Chosen with ASP.net: pre filling and saving multiple selections

The problem
– You want to use Chosen to snazz up your dropdowns.
– You need to store the selected values.
– You need to prefill the selected values when the page is reloaded.
Setting up chosen: Add chosen to the project. The simplest way is to use NuGet Package Manager:

– Right click solution explorer > Manager NuGet Packages > Search for “chosen” > “Install”

Once it has installed you will need to reference it in your .aspx file:

<link href="../Content/chosen.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" src="../Scripts/chosen.jquery.js">script>

Add the chosen class to your select:
(The data-placeholder is the test shown before you make a selection)

<select class="chosen" data-placeholder="Select Recipients..." multiple="true" id="recipients" name = "recipientselect">select>

Initialise chosen:

<script type="text/javascript">
        $(document).ready(function () {
            //initialise the recipients field with Chosen
            $(".chosen").chosen();    
script>

Reading the selected fields:

In codebehind on postback we access the select using its name, and then split the results and loop through them:

 string recipients = Request.Form["recipientselect"];
        if (recipients != null) {
            string[] recList = recipients.Split(',');
            foreach (string rec in recList) {
                // save the selected recipients
            }
        }



Re-loading the selections into chosen:

Probably not the best way, but it works; I’ve set up a basic service returning the selected recipients and then added that selection to the dropdown:

function FillSelectedRecipients() {
            var docID = $("#<%= hidDocID.ClientID %>").val()

            if (docID.length > 0) {
                $.ajax({
                    type: "POST", url: "EchoService.asmx/GetRecipients",
                    data: '{"DocID": "' + $("#<%= hidDocID.ClientID %>").val() + '"}',
                    contentType: "application/json; charset=utf-8", dataType: "json",
                    success: function (msg) {
                        $("#recipients").val(msg.d).trigger("liszt:updated");
                    },
                    error: function () { 
                    }
                });
            }
        }

The recipients can be loaded in directly as json, but the chosen dropdown needs to be updated using

.trigger("liszt:updated")

in order to display correctly.