Bind Asp.Net MVC DropDownList Using Entity Framework

Bind Asp.Net MVC DropDownList Using Entity Framework

Hi friends, in this post we will learn how to Bind Asp.Net MVC DropDownList Using Entity Framework, or you can say Bind Asp.Net MVC Dropdownlist from Sql Server Database using Entity Framework, Asp.Net MVC Dropdownlist from Sql Server Database, Dynamic asp.net MVC Dropdownlist, Dynamic Dropdownlist in asp.net MVC using Entity Framework, Dynamic Dropdownlist in asp.net MVC.

1. Open Visual Studio, Click File > New > Project.

2. Select Your Preferred Language, and under that click on WEB in Left Pane, under your preferred language. Now Click on Asp.Net Web Application.

Bind Asp.Net MVC DropDownList Using Entity Framework

3. Provide a name to your project and specify location of project.

4. On OK click new window will open, now choose MVC and click on OK. It will add required files and folder automatically in the solution . So a default running MVC applications is ready. But our aim is to bind dropdownlist from database using entity framework.

Dynamically Bind DropDownList in Asp.Net MVC

5. Now right click on project name in solution explorer and go to ADD > New Item. Pop up window will open click on Data in left pane and choose ADO.Net Entity Data Model and click OK.

Dynamically Bind DropDownList in Asp.Net MVC

6.  A New Entity Data Model Wizard dialog box will open. Select Generate Model from Database and click next. Click on New Connection and Enter SQL Server Credentials. On Next Screen select Table you want to use. Click on Finish.

How to dynamically bind Asp.Net MVC Dropdownlist from Sql Server Database using entity framework

Asp.Net MVC Dropdownlist from Sql Server Database using entity framework

Asp.Net MVC Dropdownlist from Sql Server Database

7. EDMX and Model files are added in the solution as shown in image below.

8. Now expand Controllers and double click on HomeController.cs to edit.

9. Now on Index action code will be:

public ActionResult Index()
{
agroshoponlineEntities db = new agroshoponlineEntities();
ViewBag.Category = new SelectList(db.category_master, "category_id", "category_name");
return View();
}

10. Expand Views and open Index.cshtml and use below code:

<div class="col-md-2">
Select Category:
</div>
<div class="col-md-2">
@Html.DropDownList("category","Select")
</div>