Binding Dropdownlist With Database In MVC

This article shows how to bind a dropdownlist in various ways with a database.

I know you have seen many articles regarding dropdownlist but no one is showing binding with a database.

I saw most developers coming from webform development and not find it easy to use this HTML control. There are server controls in ASP.NET webforms that are easy to bind.

And in the same way in an Edit Form this shows how to dropdownlist selected.

I am using dapper to access the data from the database. Please do not be shocked, its an ORM and easy to use compared to Entity Framework.

But it is the same as Entity Framework. Do not worry, in the same way you can use this in Entity Framework.

If you want to see how to do a Cascading Dropdownlist then here is the link, please check it.

http://www.c-sharpcorner.com/UploadFile/4d9083/creating-simple-cascading-dropdownlist-in-mvc-4-using-razor/

Various ways to do the binding

  1. Using @html.DropDownList Model

    1. @Html.DropDownList("Mobiledropdown1", Model.MobileList)  

  2. Using @html.DropDownList with Viewbag

    1. @Html.DropDownList("Mobiledropdown2", ViewBag.VBMobileList as SelectList) 

  3. Using @html.DropDownListFor With Model

    1. @Html.DropDownListFor(M => M.MobileList, new SelectList(Model.MobileList,"Value""Text")) 

  4. Using @html.DropDownList With hardcode values on View / with ViewBag.
    1.
    1. @Html.DropDownList("Mobiledropdown3"new List<SelectListItem>  
    2.      { new SelectListItem { Text = "HTC DESIRE", Value = "1", Selected=true},  
    3.        new SelectListItem { Text = "Moto G", Value = "2"},  
    4.        new SelectListItem { Text = "GO mobiles", Value = "3"}  
    5.        }, "Select Mobile"

    2.
    1. @Html.DropDownList("Dr",ViewData["MyhardcodeValue"as List<SelectListItem>) 

    Here is a table snapshot . I am also providing to you the table script in an attachment.


Let's start by creating the Model first.

I am adding the model with the name Mobiledata.

Adding all the fields that are present in the SQL Table and SelectList to get the data in the Collection.

  1. [Table("Mobiledata")]  
  2.     public class Mobiledata  
  3.     {  
  4.         [Key]  
  5.         public int MobileID { getset; }  
  6.         public string MobileName { getset; }  
  7.         public string MobileIMEno { getset; }  
  8.         public string MobileManufactured { getset; }  
  9.         public Nullable<decimal> Mobileprice { getset; }  
  10.         [NotMapped]  
  11.         public SelectList MobileList { getset; }  
  12.        
  13.     } 

For a Dapper User I am adding another class with the name MobileContext.

  1.     public class MobileContext  
  2.     {  
  3. SqlConnection con = new   SqlConnection(ConfigurationManager.ConnectionStrings["MYConnector"].ToString());  
  4.   
  5.       public IEnumerable<Mobiledata> GetMobileList()  
  6.       {  
  7.       string query = "SELECT [MobileID],[MobileName]FROM [MobileDB].[dbo].[Mobiledata]";  
  8.             var result = con.Query<Mobiledata>(query);  
  9.             return result;  
  10.       }  
  11.     } 

This class will return an Enumerable list of MobileData.

We are complete with the Model part. I will now show you the Controller part.

I am adding the Controller with the name MobileDisplayController.



After adding the Controller you will see a similar view.

I have also added a Mobilecontext class; you can view it here.

MobileDisplayController.cs



After adding the Controller now the main purpose is to pass a value to the view from the Controller.

Let's pass values.

  1. MobileContext MCon = new MobileContext(); 

The following is the MobileContext class for getting the Enumerable List .

  1. Mobiledata MD = new Mobiledata(); 

Mobiledata is the model that I am passing to the View.

In that Model you can see MobileList that is Enumerable.

  1. MD.MobileList = new SelectList(MCon.GetMobileList(), "MobileID""MobileName"); 

Now to that MobileList I am passing SelectList with Enumerable List from MobileContext Class and also value and Text that I want to display.

First way to Binding Dropdownlist.

MobileDisplayController.cs



After passing the data now to display it in the View.

For that add a View by right-clicking inside ActionResult and select AddView and provide its name as Index.



After adding the View add a Namespace to the Model as shown below.



The following is a snapshot of the binding of the Dropdownlist:



Here we can directly access the MobileList from the Model.

Now just run the application and just check it.



It's done.

Second way to Bind Dropdownlist

Now in the second way we just need to pass the same list to the Viewbag.

As in the first way we have passed a value to the model now in the same way we would pass a list to the Viewbag.


  1. ViewBag.VBMobileList = new SelectList(MCon.GetMobileList(), "MobileID""MobileName");   
  2. // Viewbag 

For your reference you can run and check it.

Third way to Binding Dropdownlist

In the third way everything will be the same but the binding to the DropdownlistFor is different.

Using the same model that was used for the first way to do the binding .

  1. MD.MobileList = new SelectList(MCon.GetMobileList(), "MobileID""MobileName"); 

Here is a snapshot to show how to bind.



For binding the dropdownlist we require a LINQ expression and IEnumreable list.

As you have seen if you are creating a view directly using the scafffloding technique then you can see a LINQ lamda expression.

For example. @Html.TextboxFor(m => m.MobileName)

Fourth way to Binding Dropdownlist

In the last way we can pass hardcoded values to the dropdownlist on the View only.

1. Directly View



2. Binding directly using ViewBag

The same List<SelectListItem> that we pass in the view directly can also be sent from the Controller and bound directly using a ViewBag.



Now we completed the binding of the Dropdownlist.

Now you may have a question of how to read the Dropdownlist values.

You can read using a FromCollection or Model.

Here you need to create a Post Method .

If you want to read all the values of the dropdownlist or any HTML control then you will get in FormCollection.

Post method from MobileDisplayController:



How to set a selected value of Dropdownlist on EditPage

Here I am showing how to show a selected dropdownlist value on Edit Page because this small thing will take time when you are new to this kind of technology.



Get the method of the Edit page from MobileDisplayController.



Output after editing.



How to add a Select at the top of the selection list.

Just add a String value at the end of the Dropdownlist.

  1. <div class="editor-field">  
  2.    @Html.DropDownList("Mobiledropdown1", Model.MobileList, "Select Mobile")  
  3. </div> 




Enjoy programming and Enjoy Sharing.

Up Next
    Ebook Download
    View all
    Learn
    View all