Thursday, April 2, 2009

How to implement Cascading dropdowns using JQuery, AJAX and ASP.NET

The primary purpose of this article is to showcase how to load dropdowns dynamically from the client side, bring the data from the server using ASP.NET and AJAX. The script will be written using JQUERY.
For those who want a smaller sample application to go through to get a start on JQUERY / AJAX / ASP.NET combination can read it from (http://sites.google.com/site/spyderhoodcommunity/tech-stuff/howtosubmitaformusingjqueryviaajaxtoanaspnetandreceivetheresponse) and if there is a need to post comments or questions you can read it from (http://kartiksehgal.blogspot.com/2009/04/how-to-submit-form-using-jquery-via.html). Sites.google.com does not facilitate commenting by viewers as yet. As with the previous article, this article too does not require the user to set up any database by creating all the sample data within the code itself.
Comments or Questions, both are appreciated.
If there is a need to get into JQuery reference, a good start point will be the site http://jquery.com/.
Source code can be downloaded from contactmanagement_20090402.zip. This source code contains the above mentioned article’s source code also but is no where interconnected.
Solution
Steps
  1. Download the zip and set up the application under IIS as an ASP.NET 2.0 virtual directory under the default website
  2. Open the site in visual studio 2005 and check if you can see all the files as depicted in the solution above
  3. Open the SendEmailToContact.htm in your browser to run and see the form working
Cascading Dropdowns
The two dropdowns are highlighted below. Notice that a default option "Loading contacts..." is added to the contact dropdown.

<tr>

<td><select id="DdlContact" name="DdlContact"><option value="loading">Loading contacts...option>select>td>

<td><select id="DdlEmail" name="DdlEmail"><option value="loading">Loading contact emails...option>select>td>

tr>


Observe the following lines in JQUERY,

$.post("SendEmailToContact.aspx?StrMethodName=GETCONTACTS", {},
           function (response)
           {
                 $("#DdlContact").html(response);
                 $.post("SendEmailToContact.aspx?StrMethodName=GETCONTACTEMAILS", { DdlContact: $("#DdlContact").val()},
                 function (response) { $("#DdlEmail").html(response);});
           }
         );

$.post expects 3 arguments
a.       The name of the page to which the form will be posted
b.      The arguments which need to be posted
c.       The function to be called on receiving the response

Here, we have appended a Query String to the SendEmailToContact.aspx which will receive the data requests. StrMethodName is checked at the code behind level and if blank, error code -2 is returned. However, in this sample we are not doing any error handling or validation. That will be handled in a subsequent article. 

"GETCONTACTS" is a specific text that is matched in the code behind and if found, then the relevant method is called to get the data.

if (!String.IsNullOrEmpty(Request.QueryString["StrMethodName"]))

{
    strMethodName = Convert.ToString(Request.QueryString["StrMethodName"]);
}

if (strMethodName.Length > 0 && strMethodName.ToUpper().Equals("GETCONTACTS"))
{
    Response.Write(CreateContactDropDownOptions(GetContacts()));
}
elseif (strMethodName.Length > 0 && strMethodName.ToUpper().Equals("GETCONTACTEMAILS"))
{
    if (i32Contact > Int32.MinValue)
    {
        Response.Write(CreateEmailDropDownOptions(GetEmailsOfContact(i32Contact)));
    }
    else
    {
        Response.Write("-1");
    }
}
elseif (strMethodName.Length > 0 && strMethodName.ToUpper().Equals("SENDEMAIL"))
{
    Response.Write("

To: " + strEmail + "

Subject: " +

    strEmailSubject + "

" + strEmailMessage + "

");
}
else
{
    Response.Write("-2");
}

Once the data is received from the call, $("#DdlContact").html(response); ensures that the response sent from the server is set into the HTML of the select option (replacing any existing HTML. 

html() is a JQUERY function to get and set the innerHTML of an element. To keep the scripting simple, we just created option tags in the server itself and sent it to the calling function.

private String CreateEmailDropDownOptions(List<ContactEmail> PrmContactEmails)
{
    System.Text.StringBuilder strBldOptions = new System.Text.StringBuilder();
    foreach (ContactEmail contactEmail in PrmContactEmails)
    {
        strBldOptions.Append(" + contactEmail.StrEmail + "\">" + contactEmail.StrEmail + "");
    }
    return strBldOptions.ToString();
}

The next step is to take the selected value of the contacts dropdown, which is the first one by default, and make a similar call for the Emails of the selected contact

$.post("SendEmailToContact.aspx?StrMethodName=GETCONTACTEMAILS", { DdlContact: $("#DdlContact").val()},
                 function (response) { $("#DdlEmail").html(response);});

Here we had to pass the selected value of DdlContact. The JQUERY function, val() gets the value of selected option. 

Note: No matter what way we load the dropdowns, up to about 2000 options it works fine. The moment we start going higher, even though the html is sent within seconds to the client side, the browser becomes sluggish in rendering the drop down. When the options were increased beyond 4000, the browser stopped responding even though response had come back in a few seconds.

Please feel free to post questions / comments for this article at the following link.

Screen shots of the application in action

 Initial screen with contact and their emails waiting to be loaded


 On the select of a contact, an AJAX call is made to load the corresponding emails


 Emails are loaded almost instantaneously


 Creating a sample content


 Sample content is received from server in formatted manner


No comments:

Post a Comment