In this article I will explain with an example, how to set selected value of DropDownList from Model (Database) using Entity Framework in ASP.Net MVC Razor.
Initially, the DropDownList will be populated from Database using Entity Framework and then the DropDownList item to be displayed as Selected will be set in Model and finally the Model will be used to populate the DropDownList in ASP.Net MVC Razor.
Database
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.
Entity Framework Model
Once the Entity Framework is configured and connected to the database table, the Model will look as shown below.
Controller
The Controller consists of the following Action method.
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 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.
Once the List is fetched, the record with ID 2 is marked as Selected so that in the DropDownList it will be shown as Selected Item.
public class HomeController : Controller
{
// GET: Home
public ActionResult Index()
{
List<SelectListItem> customerList = GetCustomers();
//Set the Item with ID '2' as Selected.
customerList.Find(c => c.Value == "2").Selected = true;
return View(customerList);
}
private static List<SelectListItem> GetCustomers()
{
CustomersEntities entities = new CustomersEntities();
List<SelectListItem> customerList = (from p in entities.Customers.AsEnumerable()
select new SelectListItem
{
Text = p.Name,
Value = p.CustomerId.ToString()
}).ToList();
return customerList;
}
}
View
Inside the View, in the very first line Generic list of SelectListItem class is declared as Model for the View.
The DropDownList is generated using the Html.DropDownList Html Helper method.
The first parameter is the Name of the DropDownList, the same will also be used to fetch the selected value of the DropDownList inside Controller when the Form is submitted.
The second parameter is the Model class for populating the DropDownList i.e. its source of data.
@model List<SelectListItem>
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width"/>
<title>Index</title>
</head>
<body>
@Html.DropDownList("ddlCustomers", Model)
</body>
</html>
Screenshot
Downloads