Link to home
Start Free TrialLog in
Avatar of ziorrinfotech
ziorrinfotech

asked on

how to load values of dropdown list control using jquery in asp.net website

I have a web page which contains a country dropdown list which gets filled on page load.
I want to load the state list when a country is selected using jquery,

is it possible with sever control as both country and state list controls are server side.

if yes pls provide me some examples
Avatar of hb69
hb69

Let's presume you are getting the info from the drop down list from a db ... just to make it interesting.

FIRST - the JQUERY.  Get the data from (in this case) a generic handler.  We make an AJAX GET request (passing dummy data to the handler ... since I can't predict your data architecture).  When the info has been passed successfully, we have a callback function that hanldes the population of the dropdown.

        // asp dropdownlist
        $.getJSON(
            '/generichandlers/jq_GetFromDB.ashx',
            {firstname:'Mista', lastname:'Bigg', age:43},
                function(data) {
                //callback
                populateOffices(data);
                }
        );

I'm setting this up with a hander because it will be useful for those using databases who want to call server-side functionality without the burden of viewstate or ineffective .net postbacks.  Here's the JSON string/array that is being returned from the Generic Handler but if you don't like this just make any old array and it'll do.

context.Response.Write("{'44352' : 'East Desolation', '98872' : 'DownTown Branch', '56821' : 'South Side'}");

Here's the function that populates the asp:dropdownlist: VERY IMPORTANT you have to use the name of the control that is generated from the CLR (ctl00_ContentPlaceHolder1_drpOffices)  NOT drpOffices.

function populateOffices(genArray) {
    $.each(genArray, function(val, text) {
        $('#ctl00_ContentPlaceHolder1_drpOffices').append(
            $('<option></option').val(val).html(text)
        );
    });
}

And here's the dropdownlist:

<asp:DropDownList ID="drpOffices" runat="server" />

I am presuming you are familiar with how to set this stuff up.  
       
ASKER CERTIFIED SOLUTION
Avatar of hb69
hb69

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
I forgot to mention, if you bypass the .net postback and use JQuery AJAX then you need to put EnableEventValidation="false" in the page directive.