Basically this article would demonstrate in a step by step manner - how to populate a dropdown list in ASP.NET MVC2 using Entity Framework 4.0 using View Models and Repository Pattern. Over the course of this article we will see how to Create View Model classes to make strongly typed Views and how to use Repository pattern in Models - to specify all the Querying methods required in the application. 1. Start by Creating a new Visual Studio Solution - Open a new instance of Visual Studio 2010. Select File -> New -> Project and from the new project dialog select ASP.Net MVC 2 Web Application -> Name it -> PopulatingDDLusingEF Click Ok – and for this sample application -> Select -> "No, Do not create a unit Test Project" 2. Create ViewModel
namespace PopulatingDDLusingEF.ViewModels { public class IndexViewModel { //DDL ID public string ddlStateId { get; set; }
//DropDownList Values public List<SelectListItem> StateValue { get; set; } } }
3. Database Part
4. Setting up the Models Adding Entity Framework classes
Creating a Repository Class
namespace PopulatingDDLusingEF.Models { public class DataRepository { //Create an instance of SampleDBEntities public SampleDBEntities entities = new SampleDBEntities(); //Fetching data from table public List<SelectListItem> GetStateName() { var vStateName = (from tblState in entities.tblStates select new SelectListItem { Text = tblState.StateName, Value = tblState.StateName }); return vStateName.ToList(); } } }
5. Views
6. Controllers
public ActionResult About() { return View(); } } }
7. Compile and run the Project (F5) In this tutorial you have seen how to populate a dropdownlist in ASP.NET MVC by taking the advantage of Microsoft Entity Framework, ViewModel class and Repository pattern. I have attached the Code for this Sample application. Happy Learning!!
You need to be a premium member to use this feature. To access it, you'll have to upgrade your membership.
Become a sharper developer and jumpstart your career.
$0
$
. 00
monthly
For Basic members:
$20
For Premium members:
$45
For Elite members: