DropDown Binding With jQuery

In this article we learn Dropdown binding using jQuery. We can bind a dropdown with C# also but the performance is very slow. Performance is a big issue so if you want the performance to be good, use jQuery more in your applications.
 
jQuery
 
Halt before proceding with this article and give some time to learn jQuery. If you want to learn what jQuery is and why we need it in development, just go to the links try and try .
 
How to add reference jQuery Library:
 
Before using any function of jQuery we need the jQuery library. We need the reference in the aspx page. I provide the reference of the jQuery library in an aspx page like this: 
  1. <script src="jquery-1.6.4.js" type="text/javascript"></script> 
I have used the jQuery 1.6.4 version.
 
Make a function for getting the data:
  1. <script >  
  2.       $(document).ready(function () {                 
  3.           $.ajax({  
  4.               type: "POST",  
  5.               contentType: "application/json; charset=utf-8",  
  6.               url: "test.aspx/LoadCountry",  
  7.               data: "{}",  
  8.               dataType: "json",  
  9.               success: function (Result) {  
  10.                   $.each(Result.d, function (key, value) {  
  11.                       $("#ddlcountry").append($("<option></option>").val(value.CountryId).html(value.CountryName));  
  12.                   });  
  13.               },  
  14.               error: function (Result) {  
  15.                   alert("Error");  
  16.               }  
  17.           });  
  18.       }); 
Don't get confused, I will explain each line of code. 
  1. $(document).ready(function () {     
A page can't be manipulated safely until the document is ready. The preceding function executes after document is completely loaded in the client machine. Many functions are available to check that. 
  1. $.ajax({  
jQquery and Ajax are combined for getting and posting the data on the server. So I used the $.ajax to post to the server and get back data for binding in the dropdown list. 
  1. type: "POST"
Our page has only two conditions, one is get and the other is post.
  1. contentType: "application/json; charset=utf-8",   
 The header just denotes what the content is encoded in.     
  1. url: "test.aspx/LoadCountry"
The preceding line clear something what is this. URL holds the address of where it is connected. You can see the test.aspx is the page name and LoadCountry is a method. This method helps to connect to the database and return the data on the jQuery function.

Note:
In the URL we can't use the Master page address like Text.Master/LoadCountry. I have tried many times but every time I encounter the problem. I have no idea why we can't do this. 
  1. data: "{}",  
Data is mainly passed the parameters (data) jQuery to the code behind method. If you pass the data then there is just some change in it.
  1. data: "{'id': '" + job_id + "'}", Id is parameter and Job_id is data.
  2.  
  1. dataType: "json",  
There are the following data types supported by JSON.

Number, string, boolean, array, value, object, white space and so on. 
  1. success: function (Result) {    
  2.                        $.each(Result.d, function (key, value) {    
  3.                            $("#ddlcountry").append($("<option></option>").val(value.CountryId).html(value.CountryName));    
  4.                        });    
  5.                    },   
Success: Is a predefined function in jQuery. The result is the object value.$. Each is working like a loop. #ddlcountry is a dropdown id. In the dropdown every time append the <option></option>.
  1. error: function (Result) {    
  2.                        alert("Error");   
Error: Is executed when any type of error result is thrown.

I hope everything is clear. I am now getting to the code behind. I have already said we need a static type method.
  1. [System.Web.Services.WebMethod]  
  2.    public static List<property> LoadCountry()  
  3.    {  
  4.       return LoadCountry1();  
  5.    }   
  1. public static List<property> LoadCountry1()  //this method is a static type and list<property> is return.  
  2. {    
  3.     List<property> CountryInformation = new List<property>();  //create a reference of List<Property>.  
  4.     DataSet ds;    
  5.     using (SqlConnection con = new SqlConnection(@"Data Source=Path of the server;Initial Catalog=databaseName;                                                                                                         ntegrated Security=True"))    
  6.     {    
  7.         using (SqlCommand cmd = new SqlCommand("GetaCountryRecords", con)) //GetCountryRecords is a Stored Procedure.  
  8.         {    
  9.             con.Open();    
  10.             cmd.Connection = con;    
  11.             cmd.CommandType = CommandType.StoredProcedure;    
  12.             SqlParameter parameter = cmd.Parameters.Add("@count", SqlDbType.Int);  //@count is Stored Procedure parameter and
  13.                                                                                        this is a output parameters.  
  14.     
  15.             parameter.Direction = ParameterDirection.Output;    
  16.                   
  17.             using (SqlDataAdapter da = new SqlDataAdapter(cmd))    
  18.             {    
  19.     
  20.                 ds = new DataSet();    
  21.                 da.Fill(ds);    //Fill the dataset.
  22.             }    
  23.         }    
  24.     }   
  25. }
We check whether ds is null and why we go further.
  1. try    
  2. {    
  3.     if (ds != null)    
  4.     {    
  5.         if (ds.Tables.Count > 0)    
  6.         {    
  7.             if (ds.Tables[0].Rows.Count > 0)    
  8.             {    
  9.                 foreach (DataRow dr in ds.Tables[0].Rows)    
  10.                 {    
  11.                     CountryInformation.Add(new property()    
  12.                     {    
  13.                         CountryId = Convert.ToInt32(dr["CountryId"]),    
  14.                         CountryName = dr["CountryName"].ToString()    
  15.                     });    
  16.                 }    
  17.             }    
  18.         }    
  19.     }    
  20. }   
Stored Procedure
  1. GO  
  2.    ALTER procedure  [dbo].[GetaCountryRecords] (@count int out)  
  3. as  
  4.    begin  
  5.    select @count=COUNT(*) from Tbl_Country  
  6.    select CountryId,CountryName from Tbl_Country  
  7.    return @count  
  8. end 
Output:
city image
Final word:

I hope everyone has enjoyed this article. If you have any query about the code then drop your comments in the comment box. I have attached the full code with the jQuery version. You can also download it, it's fee.

Up Next
    Ebook Download
    View all
    Learn
    View all