The Self-Taught Programmer

Recipes from real-world experience with

How to Pass Extra Parameters When Using AJAX Toolkit CascadingDropDowns with a Database

leave a comment »

The Situation:

You have set up your CascadingDropDowns as shown on the ASP.NET AJAX Control Toolkit documentation here, using a web service to retrieve and populate your dropdowns. However, in addition to the value of the first dropdown, you need to pass other parameters to the web service to be used in your query.

A Solution:

The CascadingDropDown control has a mechanism for this — ContextKey. You can add it like at design time like this (note the last 2 lines):

	PromptText="Please select blah blah blah"
	ContextKey="0" />

This works great for passing a single parameter. And you can set it dynamically in the code-behind like this (make sure to include a “using AjaxControlToolkit;” in the code-behind):

CascadingDropDown ccd = (CascadingDropDown)CascadingDropDown2;
ccd.ContextKey = avalues + ";";

But what if you want to pass more than a single value?

You can always set ContextKey to a delimited string, which will work just fine. But the AJAX toolkit’s CascadingDropDown control has a function called “ParseKnownCategoryValuesString(string)”, which accepts a string delimited in this way:


And returns a StringDictionary containing the keys and their values, so you can easily use them in your code.

Here’s an example of how to use this in your web service code:

public CascadingDropDownNameValue[] GetDDdata(string knownCategoryValues, string category, string contextKey)
	// The Value of the parent DropDown is in knownCategoryValues
	StringDictionary kv = CascadingDropDown.ParseKnownCategoryValuesString(knownCategoryValues);
	int someId;
	if (!kv.ContainsKey("SomeItemName") ||
		!Int32.TryParse(kv["SomeItemName"], out someId))
		return null;

	// Other parameters are in contextKey. Must be formatted the same as knownCategoryValues
	//  (i.e., "key:value;key:value;key:value;")
	StringDictionary ck = CascadingDropDown.ParseKnownCategoryValuesString(contextKey);

	string SomeOtherThing = "";
	if (!ck.ContainsKey("SomeOtherThing") || ck["SomeOtherThing"] == null)
		return null;
		SomeOtherThing = ck["SomeOtherThing"];
	// ... do some other processing here ...
	return result;

Written by Jim McMullen

November 1, 2012 at 12:14 pm

Posted in How-To

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: