In this article I will explain with an example, how to bind (populate) Multiple Select (Multi-Select) ListBox from database using Model in ASP.Net MVC Razor.
The Multiple Select (Multi-Select) ListBox will be populated from database using Model class and the Html.ListBoxFor Html Helper method.
Database
This article makes use of a table named Fruits whose schema is defined as follows.
The Fruits table has the following records.
Note: You can download the database table SQL by clicking the download link below.
Namespaces
You will need to import the following namespaces.
using System.Configuration;
using System.Data.SqlClient;
using System.Collections.Generic;
Model
The following Model class has two properties Fruits and FruitIds.
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; }
}
Controller
The Controller consists of two 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
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 Form consists of a ListBox, and a Submit Button.
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.
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 ListBox_MVC.Models.FruitModel
@{
Layout = null;
}
<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", "Home", FormMethod.Post))
{
@Html.Label("Fruits:")
<br/>
<br/>
@Html.ListBoxFor(m => m.FruitIds, Model.Fruits)
<br/>
<br/>
<input type="submit" value="Submit"/>
}
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshot
Downloads