In this article I will explain with an example, how to bind (populate) DropDownList from ViewModel in ASP.Net MVC Razor.
The DropDownList will be populated from database using Model class and the Html.DropDownListFor 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 three properties Fruits, FruitId and Quantity.
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 DropDownList.
public class FruitModel
{
public List<SelectListItem> Fruits { get; set; }
public int? FruitId { get; set; }
public int? Quantity { 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 selected Fruit name and the Quantity 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();
var selectedItem = fruit.Fruits.Find(p => p.Value == fruit.FruitId.ToString());
if (selectedItem != null)
{
selectedItem.Selected = true;
ViewBag.Message = "Fruit: " + selectedItem.Text;
ViewBag.Message += "\\nQuantity: " + fruit.Quantity;
}
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 DropDownList, a TextBox and a Submit Button.
The DropDownList is generated using the Html.DropDownListFor Html Helper method.
The first parameter is the Lambda expression for specifying the property that will hold the Selected Value of the DropDownList when the Form is submitted.
The second parameter is the Model class property for populating the DropDownList i.e. its source of data.
Finally the third and the last parameter is the text of the Default Item of the DropDownList. If not specified there will be no default item in the DropDownList.
When the Submit Button is clicked, the Form gets submitted and the value of the selected Fruit and the Quantity is sent to the Controller.
Finally the selected Fruit name and the Quantity are displayed using JavaScript Alert Message Box.
@model DropDownListFor_MVC.Models.FruitModel
@{
Layout = null;
}
<!DOCTYPE html>
<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))
{
<table>
<tr>
<td>
Fruit:
</td>
<td>
@Html.DropDownListFor(m => m.FruitId, Model.Fruits, "Please select")
</td>
</tr>
<tr>
<td>
Quantity:
</td>
<td>
@Html.TextBoxFor(m => m.Quantity)
</td>
</tr>
<tr>
<td></td>
<td>
<input type="submit" value="Submit"/>
</td>
</tr>
</table>
}
@if (ViewBag.Message != null)
{
<script type="text/javascript">
window.onload = function () {
alert("@ViewBag.Message");
};
</script>
}
</body>
</html>
Screenshot
Downloads