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

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):

<ajaxToolkit:CascadingDropDown
	ID="CascadingDropDown3"
	runat="server"
	TargetControlID="dd2"
	ParentControlID="dd1"
	PromptText="Please select blah blah blah"
	ServiceMethod="GetDDdata"
	ServicePath="WebSerivce.asmx"
	Category="ObjectName"
	UseContextKey="true"
	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:

“key:value;key:value;key:value;”

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:

[WebMethod]
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;
	}
	else
	{
		SomeOtherThing = ck["SomeOtherThing"];
	}
	
	// ... do some other processing here ...
	
	return result;
}

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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