Click here to Skip to main content
Click here to Skip to main content

Cascaded dropdown using jQuery

By , 28 May 2009
 

Introduction

In this article, I will explain how to create cascaded dropdowns using jQuery and AJAX. Cascaded dropdowns are provided by the AJAX Control Toolkit, but with this technique, you have much more control over your code, and it is quite easy to expand and implement. Also, jQuery is more lightweight than the AJAX Control Toolkit.

Using the code

The server-side method call by jQuery is as follows:

[WebMethod]
public static Dictionary<string, object> GetFileType(string x, string y)
{
    try{
        Dictionary<string, object> dd = new Dictionary<string, object>();
        dd = GetFromDataBase("Select FiletypeId,Filetypename from M_FileType");
        return dd;
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

private static Dictionary<string, object> GetFromDataBase(string Query)
{
    try
    {
        DataSet ds = new DataSet();
        OracleConnection oCon = new OracleConnection(Your Connection String goes here);
        OracleCommand oCmd = new OracleCommand(Query, oCon);
        OracleDataAdapter da = new OracleDataAdapter(oCmd);
        da.Fill(ds);
        return HimJSON1.ToJson(ds.Tables[0]);
    }
    catch (Exception ex)
    {
        throw ex;
    }
}

In the source code, place the dropdownlists:

<asp:DropDownList ID="ddFileType" class="FillDD" 
  SuccessMethod="outputDT" TargetControl="ddFileColumn" 
  ErrorMethod="ShowError" Item="FILECOLID" 
  Description="NAME" 
  ServerMethod="Default.aspx/GetFileColumn" width="300 px" 
  runat="server">
    <asp:ListItem Value="-1">---Select---</asp:ListItem>
</asp:DropDownList> 

Here, you will see some extra attributes:

  • SuccessMethod: It will be called on successful execution of the server-side method.
  • ErrorMethod: It will be called on exception thrown by the server-side method.
  • TargetControl: ID of the child dropdown which will be bound on the selected index change of the parent dropdown.
  • Item: Item field of the child dropdown which will be bound to the table column returned by the datatable.
  • Description: Description field of the child dropdown which will be bound to the table column returned by the datatable.
  • ServerMethod: Name of the server-side method which will be called by jQuery.

Exploring the JS code

  • function outputDT: This function is called when a successful result has been returned by the server-side method. In this method, I have called the BindDropdown() method which takes care of binding the child drop down. You can modify this method to implement any additional functionality.
  • function ShowError: This function is called when there is any exception thrown by the server-side method. You can modify this function to handle exceptions gracefully.
  • $('.FillDD').change(function(e): This will be called every time on the selected index change of the dropdown which has an attribute class="FillDD".

Note: Instead of using a server-side method, you can also use a Web Service.

Here, as you can see, it requires only writing some attributes to your parent dropdown and you are ready to use the cascaded dropdowns.

Points of interest

In the source code, you will find two files in the App_code folder. In these, I have implemented two different approaches to convert a datatable to JSON which you will find quite interesting and useful. You can use these classes not only here but in any project where you want to convert a datatable to JSON.

Any suggestions and improvements will be highly appreciated.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

himanshu2561
Web Developer
India India
Member
g

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
Questionnot working on firefox?membermedyx16 Aug '09 - 22:26 
Good job!
but it has problem in Firefox i think
the error is in this line:
eval(ErrorMethod + "()");
AnswerRe: not working on firefox?memberhimanshu256117 Aug '09 - 0:54 
Hi,
thanx for bringing this problem to my notice...
As i implement custom attributes in this article but there is the problem in the way i use them..So replace this
this.ServerMethod
with
this.getAttribute("ServerMethod")
Note:Replace all this.attribute with above method.
 
I will update my code shortly... Big Grin | :-D
 
himanshu

GeneralRe: not working on firefox?membermedyx17 Aug '09 - 1:08 
Hi
tnx its working Smile | :)
GeneralRe: not working on firefox?memberhimanshu256117 Aug '09 - 1:45 
Thumbs Up | :thumbsup:
 
himanshu

GeneralMy vote of 1 [modified]membernsimeonov1 Jun '09 - 15:09 
When publishing an article that may serve as example for others you should at least take a deep breath and take a look at what you're uploading. Do you have any rational explanation for putting HimJSON.cs and HimJSON1.cs and WTF stands the "1" for?
 
Additionally the classes have no comments, default code snippets are left in file:
 

<pre>/// &lt;summary&gt;
/// Summary description for HimJSON
/// &lt;/summary&gt;
public class HimJSON
{
public HimJSON()
{
//
// TODO: Add constructor logic here
//
}
</pre>
 
Parameter-less queries concatenating the sql like: GetFromDataBase("Select FilecolId,Name from M_FileColumn where filetypeid='" + Param + "'"); are one of the worst thing you can do to a database and are the most frequent cause for SQL injection attacks. Especially the way you did it.
 
Additionally hard-coded connection strings etc. are far from best practices... Again - when writing an article with educational purposes - stop for a moment and think what you're teaching others.
 
I suggest, that you revise your code and clean it up a bit before too many people saw it.
 
modified on Monday, June 1, 2009 9:17 PM

GeneralRe: My vote of 1memberhimanshu25611 Jun '09 - 19:29 
I hope u understand that this article is not about coding standards and guidelines.The code towards which u are pointing is only for informative purpose and u can change according to ur coding practices(because it is not that difficult Smile | :) ).
 
Just check default.js in source code and if u have any problem and suggestion in that than reply.
 
himanshu

GeneralMy vote of 1memberMR_SAM_PIPER1 Jun '09 - 15:07 
Very poor server code, doesn't explain the jQuery side at all.
GeneralRe: My vote of 1memberhimanshu25611 Jun '09 - 19:14 
If you want to learn about Jquery,Check this
http://docs.jquery.com/Main_Page[^].
 
This article is about cascaded dropdown using Jquery.So,my main concern is Javascript code not server side code[Hope u know Jquery is written in Javascript].
 
Thanks for ur views.
 
himanshu

GeneralGood stuffmemberMatt Sollars29 May '09 - 4:02 
I especially like seeing that more people are using custom attribute in their HTML.
 

Matt
www.geekfreeq.com
 
Help my dad get a Wii at MyDadNeedsAWii.com

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web03 | 2.6.130523.1 | Last Updated 28 May 2009
Article Copyright 2009 by himanshu2561
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid