Simply Create Dropdown List From Database In MVC 5.0

Introduction

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.

MVC

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]  

MVC

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.

MVC

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

MVC

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.

MVC

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

MVC

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;    
  6.     
  7. using Webtest1.Models;    
  8. namespace Webtest1.Controllers    
  9. {    
  10.     public class HomeController : Controller    
  11.     {    
  12.         demo2Entities1 ds = new demo2Entities1();    
  13.             
  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.         ViewBag.data = items;  
  7.     }  
  8.              
  9.     return View();  
  10. }  

And now, add new View.

MVC

MVC

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

MVC

Compile your code and run it.

MVC

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


Similar Articles