Use DropDownList Dynamically Using Ajax

In this article we will learn how to use dropdownlist dynamically using Ajax.

Before starting the topic I assume that you are familiar with jQuery and MVC. If you are not familiar with this I strongly recommended you that first learn jQuery and MVC basics, then start reading this article.

As we all know, to add a value with a HTML dropdown list statically is very easy. It is done directly using a “select” tag , but when we have a requirement to add the data in HTML dropdownlist dynamically then the things change. At that time we must load the data from the database.

Let me tell you step-by-step how to load the data dynamically from a database to a HTML dropdown list with a simple example.

Step 1

In the very first step you need to create a table in your database.

For my example I have created a table called IBank.

Let's create this table with the following command in SQL Server:

  1. Create table IBank (iBid int, sBName varchar(50));  
Insert some data into this table, to do this run the following command:
  1. Insert into IBank(iBid, sBName)  
  2. values  
  3. (001, 'SBI'),  
  4. (002, 'ICCI'),  
  5. (003, 'HDFC')  
Step 2

In the second step we need to create a view with one Dropdown control.

To do this I added an ActionResult in my controller named DynamicDropdown.
  1. public ActionResult DynamicDropDown()   
  2. {  
  3.     return View();  
  4. }  
Then we create a view for this ActionResult. In that view add the following code.
  1. <body>  
  2.     <div>  
  3.         <label>Select Bank :</label>  
  4.     </div>  
  5.     <div>  
  6.         <select class="form-control" id="op1">  
  7.             <option selected="selected">Select</option>  
  8.         </select>  
  9.     </div>  
  10. </body>   

And in the head section add the following script file.

  1. <script src="~/Scripts/jquery-2.1.4.js"></script>  
Note

If you forget to add this jQuery script file then the code doesn't work.

Step 3

In the third step we do an Ajax call, so when the page is loaded only the dropdown list highlighted with data is coming from the database.

To do Ajax call we need to write the following code in the head section.
  1. < script > $(document).ready(function()   
  2. {  
  3.     $.ajax({  
  4.         url: "Home/GetData",  
  5.         datatype: "JSON",  
  6.         type: "Get",  
  7.         success: function(data) {  
  8.             debugger;  
  9.             for (var i = 0; i < data.length; i++) {  
  10.                 var opt = new Option(data[i].Bname);  
  11.                 $("#op1").append(opt);  
  12.             }  
  13.         }  
  14.     });  
  15. }); < /script>  
Note

Hear GetData is a method that is defined under Controller Home. This method is basically used for the purpose to get the data from the database. Don't worry about this method I will define it in next step.

Here in the preceding Ajax call inside “success: function()” I used the append method of jQuery to append the data to HTML dropdown list; “op1” is the id of our dropdownlist .

Step 4

In step 4 we need to define this GetData() method under our home controller and this method returns a JSON type of data.

Note

Before adding the GetData() method first add a class under model with one property named as BankDetails .

Add the following code inside it:
  1. Public Class BankDetails   
  2. {  
  3.     Public string Bname   
  4.     {  
  5.         get;  
  6.         set;  
  7.     }  
  8. }  
After creation of this class add the namespace in other words using YourProjectname.Model. Then add the following code inside the controller.

Just write the code as it is and only make change in the database connection part.
  1. public JsonResult GetData()   
  2. {  
  3.     List < BankDetails > lstBank = new List < BankDetails > (); //Hear we Create BankDetails class type list which we defines inside model.  
  4.   
  5.     con = new SqlConnection("User Id=sa;Password=focus123;Database=SURYADB;Data Source=FOCUS-DEV-0001\\SQLSERVER2012"); // Write your DB connection .  
  6.     //cmd = new SqlCommand("select * from IBank", con);  
  7.     DataSet ds = new DataSet();  
  8.     da = new SqlDataAdapter("select * from IBank", con);  
  9.     da.Fill(ds);  
  10.     for (int i = 0; i < ds.Tables[0].Rows.Count; i++)   
  11.     {  
  12.         BankDetails ba = new BankDetails();  
  13.         ba.Bname = ds.Tables[0].Rows[i]["sBName"].ToString();  
  14.         lstBank.Add(ba);  
  15.     }  
  16.     return Json(lstBank, JsonRequestBehavior.AllowGet);  
  17. }  
Now when you write the preceding code, run the page. You will get the dynamic dropdownlist with filled data from the database.

For your reference I have given you complete code once again. Just understand it and use it as it is, don't forget to add the jQuery file v 2.1 (the latest one or better) and add the model namespace inside the controller.

In the Model folder add the class called BankDetails and add the following code:
  1. Public string Bname {getset;}  
In Home Controller add the following code:
  1. public ActionResult DynamicDropDown() {  
  2.     return View();  
  3. }  
  4. public JsonResult GetData() {  
  5.     List < BankDetails > lstBank = new List < BankDetails > ();  
  6.   
  7.     con = new SqlConnection("User Id=sa;Password=focus123;Database=SURYADB;Data Source=FOCUS-DEV-0001\\SQLSERVER2012");  
  8.     //cmd = new SqlCommand("select * from IBank", con);  
  9.     DataSet ds = new DataSet();  
  10.     da = new SqlDataAdapter("select * from IBank", con);  
  11.     da.Fill(ds);  
  12.     for (int i = 0; i < ds.Tables[0].Rows.Count; i++) {  
  13.         BankDetails ba = new BankDetails();  
  14.         ba.Bname = ds.Tables[0].Rows[i]["sBName"].ToString();  
  15.         lstBank.Add(ba);  
  16.     }  
  17.     return Json(lstBank, JsonRequestBehavior.AllowGet);  
Then just right-click on DynamicDropdown and create a view; after the view is created add the following code:
  1. <head>  
  2.     <script src="~/Scripts/jquery-2.1.4.js"></script>  
  3.     <script>  
  4. $(document).ready(function () {  
  5. $.ajax({  
  6. url: "Focus8/GetData",  
  7. datatype: "JSON",  
  8. type: "Get",  
  9. success: function (data) {  
  10. debugger;  
  11. for(var i=0;i  
  12.         <data.length;i++)  
  13. {  
  14. var opt = new Option(data[i].Bname);  
  15. $("#op1").append(opt);  
  16. }  
  17. }  
  18. });  
  19. });  
  20.   
  21.         </script>  
  22.     </head>  
  23.     <body>  
  24.         <div>  
  25.             <label>Select Bank :</label>  
  26.         </div>  
  27.         <div>  
  28.             <select class="form-control" id="op1">  
  29.                 <option selected="selected">Select</option>  
  30.             </select>  
  31.         </div>  
  32.     </body>  
Then run your application to get the result.

If you get an error, mention it in the comments section.

I hope this article will help you, don't forget to send me your suggestion that would help me in improving myself.