Simply Create Dropdown List From Database In MVC 5.0


In this article, we are learning how to create dropdown with the help of Entity Framework from database. We will be using select-View. Let’s start.

Step 1

Firstly, we are creating a table in our database. Here, my table name is college.


The college table has two files named - collegeid and collegename.

Now, we have created select-view in database. 

  1. CREATE VIEW [dbo].[schoolname] AS SELECT collegeId,collegename FROM [college]  


Step 2

Let's go to Solution Explorer and here, we are going to create a Home controller. After that, select Model and right click.

Select Add >> New item.


After that, select the ADO.NET Entity Data Model and click on "Add" button.


Now, Entity Data Model Wizard is open. Select -> "The Generate from database" option and click Next.

Here, create a new connection and click on Next option.
Then, choose Entity Framework 5.0 and click Next.
Select Views ->stud_details and click on Finish button.


Here, check the college table and in View, we have checked our View with the name schoolname.


Now, our model is ready.

Step 3

Now, we are going to Controllers folder.

Create a home Controller. After that, open it and give reference of our Model. 
  1. using System;    
  2. using System.Collections.Generic;    
  3. using System.Linq;    
  4. using System.Web;    
  5. using System.Web.Mvc;    
  7. using Webtest1.Models;    
  8. namespace Webtest1.Controllers    
  9. {    
  10.     public class HomeController : Controller    
  11.     {    
  12.         demo2Entities1 ds = new demo2Entities1();    
  14.         public ActionResult Index()    
  15.         {    
  16.             return View();    
  17.         }     
  18. }  
Now, create the method with the name studins(). Here, we are calling the schoolname's View. Set the View bag which will carry the Data Controller to view page.
  1. public ActionResult Studins()  
  2. {              
  3.     var items = ds.schoolnames.ToList();  
  4.     if(items!=null)  
  5.     {
  6. = items;  
  7.     }  
  9.     return View();  
  10. }  

And now, add new View.



Now, click on "Add" button. After that, your View is ready. And here, your dropdown list is created; bind it with View bag.


Compile your code and run it.


Now, you can see that the dropdown is simply ready!!!.

Similar Articles