Binding Dropdown using jQuery

Binding Dropdown using jQuery

Author Bio: Amy is WordPress developer by profession. She works for WordPrax - WordPress website development company and has a strong inclination for a suite of creative endeavors. Blogging meanwhile is a new found hobby for Amy.

Binding-Dropdown-Using-jQuery

Dropdown binding is perhaps one of the best things possible with jQuery. Eventhough it is feasible to bind a dropdown list using C#, opting for jQuery to perform the job entails utmost performance and convenience. This is a post which will walk you through the steps associated with using jQuery for binding a dropdown list.

Coming to the process of binding dropdown list using jQuery

Step 1 - Add the reference jQuery Library

Prior to being able to use any particular function(s) available in jQuery, it is crucial for you to have the reference for the same within the aspx page. With jQuery 2.0 as the current working version, you can use the below line of code for providing reference of jQuery library within the aspx page:

<script src="/jquery-2.0.js" type="text/javascript"></script>

Step 2 - Use a function for fetching data from jQuery Library

Just use the below mentioned function for deriving data from jQuery Library:

<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");
    }
    });
});

Here's an explanation of the above code snippet:

$(document).ready(function () {

The above function is executed once the document has been loaded completely on the client machine. It is important to note that a page can't be manipulated securely unless the document is ready.

$.ajax({

You can combine jQuery and Ajax for getting and posting data on the server. Here, $.ajax is used for posting data to the sever and fetching data back for binding the same within the dropdown list.

  1. type: "POST",

In this tutorial, I've assumed that the page just has two conditions: get and post. The above line of code represents this assumption.

  1. contentType: "application/json; charset=utf-8",

This line of code represents as to what the content is encoded in.

  1. url: "test.aspx/LoadCountry",

Th above line of code represents that URL holds the address of location where it is connected. So, text.aspx represents the name of page and LoadCountry is the name of method which allows you to connect the URL to database, followed by returning data on execution of jQuery function.

  1. data: "{}",

Usually, data is passed the parameters (data) jQuery to code that's associated with the chosen method(here, it is LoadCountry).

  1. dataType: "json",

This line of code represents that the all data types used in the explained example are supported by JSON. Some popular data types supported by JSON include: number, boolean, string, value, array, white space, object and many more.

success: function (Result) {
    $.each(Result.d, function (key, value) {
        $("#ddlcountry").append($("<option></option>").val(value.CountryId).html(value.CountryName));
    });
},

In the above code snippet, Success is a pre-defined function available in jQuery. Also, the result is the object value $.Each which works in the form of a continuous loop until the desired values are returned. Within the lines of code:

$("#ddlcountry").append($("<option></option>").val(value.CountryId).html(value.CountryName));

#ddlcountry is the id of the 'country' drop-down

append($(“<option></option>”).val(value.CountryId).html(value.CountryName));

represents that new options have been added into the dropdown list and their respective values are represented by value.CountryId and value.CountryName.

error: function (Result) {
    alert("Error");

Here, Error is also a jQuery function which is executed each time an error result is derived from executing the function.

Now, here is the code behind the above mentioned function:

// Country POCO 
class public class Country { 
    public int CountryID {get; set;} 
    public string CountryName {get; set;} 
}
[System.Web.Services.WebMethod] 
    public static List<Country> LoadCountry() { 
return LoadCountries(); 
}

The above code represents the static type method used for executing the function.

The entire code snippet is shown below:

/// <summary> 
/// This method returns a list of Countries 
/// </summary> 
/// <returns>List<Country></returns> 

public static List<Country> LoadCountries() { 
//create a reference of List<Property>. 
List<Country> CountryInformation = new List<Country>();

// Creating database context and write Linq query to fetch countries list

using (var Context = new DatabaseContext()) { 
    var list = Context.Country.ToList(); 
    if(list != null && list.Count > 0) { 
    foreach(var item in list) { 
        CountryInformation.Add(new Country() { 
            CountryID = item.CountryId, CountryName = item.CountryName }); 
        } 
    } 
    return CountryInformation; 
    } 
}

We're done!

Output :

Binding Dropdown using jQuery

Conclusion

Binding dropdown list on a page has always posed as a great challenge to developers. I hope the code mentioned within this post would aid you in performing the job with utmost amount of perfection.


Related Posts