In this article I will explain with an example, how to populate (bind) DropDownList from database using Entity Framework Code First Approach in ASP.Net MVC Razor.
This article will also explain how to add Default Item (Blank Item) to DropDownList at First position when populating from database using Entity Framework Code First Approach in ASP.Net MVC Razor.
Configuring Database with Entity Framework Code First Approach
I have made use of the following table Customers with the schema as follows. CustomerId is an Auto-Increment (Identity) column.
I have already inserted few records in the table.
Note: You can download the database table SQL by clicking the download link below.
You will need to configure and connect to the existing database table using Entity Framework Code First Approach.
Below is the generated DbContext class.
using System;
using System.Data.Entity;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
public partial class CodeFirstDBContext : DbContext
{
public CodeFirstDBContext()
: base("name=CodeFirst")
{
}
public virtual DbSet<Customer> Customers { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>()
.Property(e => e.Name)
.IsUnicode(false);
modelBuilder.Entity<Customer>()
.Property(e => e.Country)
.IsUnicode(false);
}
}
Controller
The Controller consists of following two Action methods.
Action method for handling GET operation
Inside this Action method, the GetCustomers method is called.
Inside the GetCustomers method, the records are fetched from the Customers table using Entity Framework Code First Approach and are copied into Generic list of SelectListItem class.
Note: The SelectListItem class which is an in-built ASP.Net MVC class. It has all the properties needed for populating a DropDownList.
A Blank item is inserted at first position (0th index) in the Generic list of SelectListItem class and it will be used to show the Default item in DropDownList.
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 ddlCustomers parameter which is also set as the Name of the DropDownList.
Then the GetCustomers method is called and the selected Customer is fetched using Lambda expression.
Finally, the Name and ID values of the selected Customer 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()
{
return View(GetCustomers());
}
[HttpPost]
public ActionResult Index(string ddlCustomers)
{
if (!string.IsNullOrEmpty(ddlCustomers))
{
SelectListItem selectedItem = GetCustomers().Find(p => p.Value == ddlCustomers);
ViewBag.Message = "Name: " + selectedItem.Text;
ViewBag.Message += "\\nID: " + selectedItem.Value;
}
return View(GetCustomers());
}
private static List<SelectListItem> GetCustomers()
{
using (CodeFirstDBContext context = new CodeFirstDBContext())
{
List<SelectListItem> customerList = (from p in context.Customers
select new SelectListItem
{
Text = p.Name,
Value = p.CustomerId.ToString()
}).ToList();
//Add Default Item at First Position.
customerList.Insert(0, new SelectListItem { Text = "--Select Customer--", Value = "" });
return customerList;
}
}
}
View
Inside the View, in the very first line Generic list of SelectListItem 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 field created using Html.DropDownList Html Helper method and a Submit Button.
The first parameter is the Name of the Html.DropDownList and the same will also be used to fetch the selected value inside Controller when the Form is submitted.
The second parameter is the Model class for populating the DropDownList i.e. its source of data.
When the Submit Button is clicked, the Form gets submitted and the Name and ID values of the selected Customer is sent to the Controller.
Finally, the Name and ID values of the selected Customer are displayed using JavaScript Alert Message Box.
@model List<SelectListItem>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
</head>
<body>
@using (Html.BeginForm("Index", "Home", FormMethod.Post))
{
@Html.DropDownList("ddlCustomers", Model)
<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