In this article I will explain with an example, how to bind (populate)
Multiple Select (Multi-Select)
DropDownList with
CheckBoxes from database using
jQuery in
ASP.Net MVC Razor.
The Multiple Select (Multi-Select)
DropDownList with
CheckBoxes will be implemented using
jQuery Bootstrap Multi-Select plugin.
Download Bootstrap and jQuery Bootstrap Multi-Select Plugin
The download locations are as follows.
Bootstrap
jQuery BoosStrap Multi-Select Plugin
You will need to download the plugin files from the following location.
The complete documentation can be read on the following page.
Database
I have made use of the following table Fruits with the schema as follows.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
Model
The Model class consists of following properties.
The Fruits property is a Generic list of
SelectListItem class which is an in-built
ASP.Net MVC class. It has all the properties needed for populating a
ListBox.
public class FruitModel
{
public List<SelectListItem> Fruits { get; set; }
public int[] FruitIds { get; set; }
}
Namespaces
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
Controller
The Controller consists of following Action methods.
Action method for handling GET operation
Inside this Action method, the PopulateFruits method is called.
Inside the PopulateFruits method, the records from the Fruits table are fetched using DataReader and generic list of SelectListItem class is populated.
The FruitName is stored in the Text property while the FruitId is stored in the Value property.
Finally, the FruitModel class object is returned to the View.
Action method for handling POST operation
This Action method handles the call made from the POST function from the View.
When the Form is submitted, the posted values are captured through the FruitModel class object.
Then the PopulateFruits method is called and the selected Fruit is fetched using Lambda expression.
Finally, the multiple selected
Fruit names are set into a
ViewBag object which will be later displayed in View using
JavaScript Alert Message Box.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
FruitModel fruit = new FruitModel();
fruit.Fruits = PopulateFruits();
return View(fruit);
}
[HttpPost]
public ActionResult Index(FruitModel fruit)
{
fruit.Fruits = PopulateFruits();
if (fruit.FruitIds != null)
{
List<SelectListItem> selectedItems = fruit.Fruits.Where(p => fruit.FruitIds.Contains(int.Parse(p.Value))).ToList();
ViewBag.Message = "Selected Fruits:";
foreach (var selectedItem in selectedItems)
{
selectedItem.Selected = true;
ViewBag.Message += "\\n" + selectedItem.Text;
}
}
return View(fruit);
}
private static List<SelectListItem>PopulateFruits()
{
List<SelectListItem> items = new List<SelectListItem>();
string constr = ConfigurationManager.ConnectionStrings["Constring"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
string query = " SELECT FruitName, FruitId FROM Fruits";
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["FruitName"].ToString(),
Value = sdr["FruitId"].ToString()
});
}
}
con.Close();
}
}
return items;
}
}
View
HTML Markup
Inside the View, in the very first line the FruitModel class is declared as Model for the View.
The View consists of an
HTML Form which has been created using the
Html.BeginForm method with the following parameters.
ActionName – Name of the Action. In this case the name is Index.
ControllerName – Name of the Controller. In this case the name is Home.
FormMethod – It specifies the Form Method i.e. GET or POST. In this case it will be set to POST.
The
ListBox is generated using the
Html.ListBoxFor Html Helper method.
The first parameter is the
Lambda expression for specifying the property that will hold the selected values of the
ListBox when the Form is submitted.
The second parameter is the Model class property for populating the
ListBox i.e. its source of data.
Bootstrap Multiselect jQuery Plugin implementation
First, the
jQuery and the
JS and
CSS files of the
Bootstrap plugin and the
jQuery Bootstrap Multi-Select plugin are inherited.
Inside the
jQuery document ready event handler, the
jQuery Bootstrap Multi-Select Plugin is applied to the
ListBox element.
Form Submission
When the
Submit Button is clicked, the Form gets submitted and the values of the selected
Fruits are sent to the Controller.
Finally, the multiple selected
Fruit names are displayed using
JavaScript Alert Message Box.
@model CheckBox_DropDownList_MVC.Models.FruitModel
@{
Layout = null;
}
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.Label("Fruits:")
<br />
<br />
@Html.ListBoxFor(m => m.FruitIds, Model.Fruits, new { @class = "listbox" })
<br />
<br />
<input type="submit" value="Submit" />
}
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/js/bootstrap.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/css/bootstrap-multiselect.css" rel="stylesheet" type="text/css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-multiselect/0.9.13/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>
Screenshot
Downloads