Translate

Monday, 12 September 2016

Multiselect using jquery chosen plugin

Multiselect dropdownlist with jquery chosen plugin:


ActionResult at controller:


public ActionResult ChosenMultiselect()
        {
            return View();
        }


 Json data to bind dropdown:


        public ActionResult ListCountries()
        {

            List<string> category = new List<string>();
            StringBuilder sb=new StringBuilder();
            for (int i = 0; i <10; i++)
            {
              
                string country="Country"+i;
                    sb.Append("<option value="+country+ ">"+country+"</option> ");
               
            }
            return Json(sb.ToString(), JsonRequestBehavior.AllowGet);


        }

View:


@{
    ViewBag.Title = "ChosenMultiselect";
}

<h2>ChosenMultiselect</h2>
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<link href="@Url.Content("~/Content/MultiSelect/chosen.css")" rel="stylesheet" />
<script src="@Url.Content("~/Content/MultiSelect/chosen.jquery.js")"></script>

<script>
    jQuery(document).ready(function () {
        jQuery(".chosen").data("placeholder", "Select a Category...").chosen();
    });
    $(document).ready(function (event) {

        var url = '@Url.Action("ListCountries", "Home")';

            $.getJSON(url, function (options) {
                $("#ddlcountry").html(options);
                $('#ddlcountry').trigger('liszt:updated');
            });
            $("#btnSearch").click(function () {
                alert($("#ddlcountry").val());
            });
        });
</script>
<div>
    <div class="selectBox">

        <select class="chosen" id="ddlcountry" multiple="true" style="width: 210px; height: 42px" name="country">
        </select>
        <input type="button" id="btnSearch" value="Search" />
    </div>
</div>

Output: