Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / database / SQL-Server / SQL-Server-2012

How to Load Data Dynamically to Html Dropdownlist

0.00/5 (No votes)
14 Aug 2015CPOL3 min read 92.8K  
In this tip, we will learn how to load data dynamically to html dropdownlist using Ajax call.

Introduction

Before starting the topic, I assume that you are familiar with jQuery and MVC, if you don’t know about this, I strongly recommended that you first learn the jQuery and MVC basics, then start reading this tip.

As we all know that to add value with Html dropdown list statically is very much easy; which done directly through “select” tag , but when we have a requirement to add the data in html dropdownlist dynamically, then the thing changes. At that time, we are required to load the data from database.

Let me tell you in a step by step manner how to load the data dynamically from database to 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 as IBank.

To do with me, let's create this table by running the following command on SqlServer.

SQL
Create table IBank (iBid int, sBName varchar(50))

Then Insert some data to this table, to do this, run the below command:

SQL
Insert into IBank(iBid,sBName) values (001,'SBI'),
                                     (002,'ICCI'),
                                     (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 as DynamicDropdown.

C#
public ActionResult DynamicDropDown()
      {
          return View();
      }

Then, we create a view for this ActionResult. In that view, add the following code:

HTML
<body>
   
            <div>
               <label>Select Bank :</label>
            </div>
            <div>
                <select class="form-control" id="op1">
                 <option selected="selected">Select</option>
                </select>
            </div>
       
</body>

And in the head section, add the following Script file.

<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 Ajax call, so when the page loaded at that time only the dropdown list highlighted with data which is coming from database.

To do ajax call, we need to write the following code in the head section.

HTML
<script>
        $(document).ready(function () {
            $.ajax({
                url: "Home/GetData",
                datatype: "JSON",
                type: "Get",
                success: function (data) {
                    debugger;
                    for(var i=0;i<data.length;i++)
                    {
                        var opt = new Option(data[i].Bname);
                        $("#op1").append(opt);
                    }
                }
            });
        });
    </script>

Note: Here, GetData is a method which is defined under Controller Home. This method is basically used for the purpose to get the data from database. Don’t worry about this method. I will define it in the next step.

Here in the above 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 we add the GetData() method, first add a class under model with one property named as BankDetails.

Add the following code inside it:

C#
Public Class BankDetails
{
Public string Bname {get; set;}
}

After creation of this class, add the namespace i.e., using YourProjectname.Model then add the following code inside the controller.

Just write the code as it is and only make changes in the database connection part.

C#
public JsonResult GetData()
        {
            List<BankDetails> lstBank = new List<BankDetails>(); //Here, 
            	// we create BankDetails class type list which we define inside model.
          
            con = new SqlConnection("User Id=sa;Password=focus123;Database=SURYADB;
            	Data Source=FOCUS-DEV-0001\\SQLSERVER2012"); // Write your DB connection
            //cmd = new SqlCommand("select * from IBank", con);
            DataSet ds = new DataSet();
            da = new SqlDataAdapter("select * from IBank", con);
            da.Fill(ds);
            for (int i = 0; i < ds.Tables[0].Rows.Count;i++ )
            {
                BankDetails ba = new BankDetails();
                ba.Bname = ds.Tables[0].Rows[i]["sBName"].ToString();
                lstBank.Add(ba);
            }
            return Json(lstBank, JsonRequestBehavior.AllowGet);
        }

Now when you write the above code, run the page you get the dynamic dropdownlist with filled data from database.

For your reference, I give you whole code once again completely just understand it and write it as it is, don’t forget to add the jQuery file v 2.1 (latest one for better) and adding the model namespace inside controller.

In Model folder, add Class called as BankDetails and add the following code:

C#
Public string Bname {get; set;}

In Home Controller, add the following code:

C#
public ActionResult DynamicDropDown()
      {
          return View();
      }

      public JsonResult GetData()
      {
          List<BankDetails> lstBank = new List<BankDetails>();
          con = new SqlConnection("User Id=sa;Password=focus123;
          Database=SURYADB;Data Source=FOCUS-DEV-0001\\SQLSERVER2012");

          //cmd = new SqlCommand("select * from IBank", con);
          DataSet ds = new DataSet();
          da = new SqlDataAdapter("select * from IBank", con);
          da.Fill(ds);
          for (int i = 0; i < ds.Tables[0].Rows.Count;i++ )
          {
              BankDetails ba = new BankDetails();
             ba.Bname = ds.Tables[0].Rows[i]["sBName"].ToString();
              lstBank.Add(ba);
          }
          return Json(lstBank, JsonRequestBehavior.AllowGet);
      }

After that, just right click on DynamicDropdown and create a view; after view created, add the following code:

HTML
<head>
   <script src="~/Scripts/jquery-2.1.4.js"></script>
  <script>
        $(document).ready(function () {
            $.ajax({
                url: "Focus8/GetData",
                datatype: "JSON",
                type: "Get",
                success: function (data) {
                    for(var i=0;i<data.length;i++)
                    {
                        var opt = new Option(data[i].Bname);
                        $("#op1").append(opt);
                    }
                }
            });
        });
    </script>
</head>
<body>
   
            <div>
               <label>Select Bank :</label>
            </div>
            <div>
                <select class="form-control" id="op1">
                 <option selected="selected">Select</option>
                </select>
            </div>
       
</body>

Then run your application. You got the result.

If you get any error, leave me a message in the "Comments" section below.

Hope this tip may helps you, don’t forget to send me your suggestions which will help me to improve myself.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)