How To Bind DropDownList In MVC Using C#

In this tutorial, I’ll show you how to bind Dropdownlist in MVC C# using Razor. Here I had take one database and feeded some dummy data. We will also see how that data comes to our dropdownlist.

INITIAL CHAMBER:

Step 1

Open Visual Studio 2010, Go to the New Project, Visual C#, Web, then ASP.NET MVC3 Web Application. After that click OK.



Step 2

After clicking OK, New ASP.NET MVC3 Project window will open. There choose - Internet Application and in View Engine Dropdown, choose Razor.



Step 3

After clicking OK, you will see something like the following image in your Solution Explorer. You need to look out for Model, Controller and View Folders, that are the main files in MVC, others are too but these are main files.



DATABASE CHAMBER

Step 4

Right Click on your Project - Add New Item, SQL Server Database and Add it. Go to your Database residing in Server Explorer - [Database.mdf]. We will create a table - tbl_Data. After that go to the database.mdf - Table and Add New table, design your table like this:



In Model

Step 5

Right Click on Models - Add New Item, then Add - ADO.NET Entity Data Model. After that Name it as Student Model.edmx and ADD it.



Entity Data Model Wizard







After all this you will see your connection string is built in web.config file. See the following image:



StudentModel.edmx:


In Controller

Step 5

Open Controller, Inside there HomeController.cs files is there. Open that and write code like this. Don’t forget to add namespace of model.

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6. using System.Data.Entity;  
  7. using MvcApplication6.Models; 

  8. namespace MvcApplication6.Controllers  
  9. {  
  10.     public class HomeController : Controller  
  11.     {  
  12.         public ActionResult Index()  
  13.         {  
  14.   
  15.             StudentDBContext db = new StudentDBContext();  
  16.             ViewBag.name = new SelectList(db.tbl_data, "id""name");  
  17.   
  18.   
  19.             return View();  
  20.         }  
  21.   
  22.         public ActionResult About()  
  23.         {  
  24.             return View();  
  25.         }  
  26.     }  
  27. }  
In View

Step 6

Open View Folder, Inside that Home folder is there. Open the Index.cshtml file and write code like this.

Index.cshtml
  1. @{  
  2. ViewBag.Title = "Home Page";  
  3. }  
  4.   
  5.   
  6. <h2>Bind DropdownList in MVC</h2>  
  7. <p>  
  8. In this tutorial we will see how to bind Dropdownlist in MVC C# using Razor.  
  9. </p>  
  10.   
  11.   
  12. @Html.DropDownList("name","--Select Name--")  
OUTPUT: [To run your Project Press Ctrl+F5]



Hope you liked it. Thank you so much for reading. Have a good day.

Up Next
    Ebook Download
    View all
    Learn
    View all