Multi Select ListBox with CheckBox in MVC

A sample for Multi Select ListBox with CheckBox in Razor MVC is explained in this article with a sample code to understand clearly about how to bind data in ListBox.

First open Visual studio -> New -> Project -> Asp.Net MVC 4 Apllication and give the application name and save it in a desired location. Select Empty application.

Create a table in sql named Flowers with two columns one for FlowerID and another one for FlowerName.

Flowers Table

Flowers Table content

Flower Model

Add a class under Model folder. Add two items in the flower class named FlowerID and Fowers

public List<SelectListItem> Flowers { get; set; }
public int[] FlowerID { get; set; }

Flower Controller

Add below code in Flower controller. In this Get and Post methods are added for Index method. In Get the list of all flowers are populated using GetAllFlowers() method. On Post method i.e submit button click the list of selected items from the list are displayed using alert box.

List of all selected items are saved in View Bag and later displayed using alert box. SelctListItem class which is an in-built ASP.Net MVC class. It has all the properties needed for populating a ListBox.

// GET: Home
        public ActionResult Index()
        {
            Flower flower = new Flower();
            flower.Flowers = GetAllFlowers();
            return View(flower);
        }

        [HttpPost]
        public ActionResult Index(Flower flower)
        {
            flower.Flowers = GetAllFlowers();
            if (flower.FlowerID != null)
            {
                List<SelectListItem> selectedItems = flower.Flowers.Where(p => flower.FlowerID.Contains(int.Parse(p.Value))).ToList();

                ViewBag.Message = "Selected Flowers:";
                foreach (var selectedItem in selectedItems)
                {
                    selectedItem.Selected = true;
                    ViewBag.Message += "\\n" + selectedItem.Text;
                }
            }

            return View(flower);
        }

        private static List<SelectListItem> GetAllFlowers()
        {
            List<SelectListItem> items = new List<SelectListItem>();
            string constr = ConfigurationManager.ConnectionStrings["ConStr"].ConnectionString;
            using (SqlConnection con = new SqlConnection(constr))
            {
                string query = " SELECT FlowerID, FlowerName FROM Flowers";
                using (SqlCommand cmd = new SqlCommand(query))
                {
                    cmd.Connection = con;
                    con.Open();
                    using (SqlDataReader sdr = cmd.ExecuteReader())
                    {
                        while (sdr.Read())
                        {
                            items.Add(new SelectListItem
                            {
                                Text = sdr["FlowerName"].ToString(),
                                Value = sdr["FlowerID"].ToString()
                            });
                        }
                    }
                    con.Close();
                }
            }

            return items;
        }

Flower View

Add below code in View of Flower.

@model Multi_Select_Listbox.Models.Flower
@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
    <style type="text/css">
        body {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
</head>
<body>
    @using (Html.BeginForm("Index", "Flower", FormMethod.Post))
    {
        @Html.Label("Flowers:")
        <br/>
        <br/>
        @Html.ListBoxFor(m => m.FlowerID, Model.Flowers, new { @class = "listbox" })
        <br/>
        <br/>
        <input type="submit" value="Submit"/>
    }
 
    <script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css"
          rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
    <link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css"/>
    <script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $('.listbox').multiselect({
                includeSelectAllOption: true
            });
        });
    </script>
    @if (ViewBag.Message != null)
    {
        <script type="text/javascript">
            window.onload = function () {
                alert("@ViewBag.Message");
            };
        </script>
    }
</body>
</html>
<script type="text/javascript"src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <link href="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css"
          rel="stylesheet" type="text/css"/>
    <script type="text/javascript" src="http://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
    <link href="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css"/>
    <script src="http://cdn.rawgit.com/davidstutz/bootstrap-multiselect/master/dist/js/bootstrap-multiselect.js" type="text/javascript"></script>

Add above script for Multi Select plugin.

Output