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:
- <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:
- <script >
- $(document).ready(function () {
- $.ajax({
- type: "POST",
- contentType: "application/json; charset=utf-8",
- url: "test.aspx/LoadCountry",
- data: "{}",
- dataType: "json",
- success: function (Result) {
- $.each(Result.d, function (key, value) {
- $("#ddlcountry").append($("<option></option>").val(value.CountryId).html(value.CountryName));
- });
- },
- error: function (Result) {
- alert("Error");
- }
- });
- });
Don't get confused, I will explain each line of code.
- $(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.
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.
Our page has only two conditions, one is get and the other is post.
- contentType: "application/json; charset=utf-8",
The header just denotes what the content is encoded in.
- 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.
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.
- data: "{'id': '" + job_id + "'}", Id is parameter and Job_id is data.
-
There are the following data types supported by JSON.
Number, string, boolean, array, value, object, white space and so on.
- success: function (Result) {
- $.each(Result.d, function (key, value) {
- $("#ddlcountry").append($("<option></option>").val(value.CountryId).html(value.CountryName));
- });
- },
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>.
- error: function (Result) {
- 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.
- [System.Web.Services.WebMethod]
- public static List<property> LoadCountry()
- {
- return LoadCountry1();
- }
- public static List<property> LoadCountry1()
- {
- List<property> CountryInformation = new List<property>();
- DataSet ds;
- using (SqlConnection con = new SqlConnection(@"Data Source=Path of the server;Initial Catalog=databaseName; ntegrated Security=True"))
- {
- using (SqlCommand cmd = new SqlCommand("GetaCountryRecords", con))
- {
- con.Open();
- cmd.Connection = con;
- cmd.CommandType = CommandType.StoredProcedure;
- SqlParameter parameter = cmd.Parameters.Add("@count", SqlDbType.Int);
-
-
- parameter.Direction = ParameterDirection.Output;
-
- using (SqlDataAdapter da = new SqlDataAdapter(cmd))
- {
-
- ds = new DataSet();
- da.Fill(ds); //Fill the dataset.
- }
- }
- }
- }
We check whether ds is null and why we go further.
- try
- {
- if (ds != null)
- {
- if (ds.Tables.Count > 0)
- {
- if (ds.Tables[0].Rows.Count > 0)
- {
- foreach (DataRow dr in ds.Tables[0].Rows)
- {
- CountryInformation.Add(new property()
- {
- CountryId = Convert.ToInt32(dr["CountryId"]),
- CountryName = dr["CountryName"].ToString()
- });
- }
- }
- }
- }
- }
Stored Procedure
- GO
- ALTER procedure [dbo].[GetaCountryRecords] (@count int out)
- as
- begin
- select @count=COUNT(*) from Tbl_Country
- select CountryId,CountryName from Tbl_Country
- return @count
- end
Output:
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.