Data Binding CascadingDropDownList
November 3, 2009 Leave a comment
The CascadingDropDownList (CDDL) is a very handy control – I have used it in a couple of different situations. I recently ran into an interesting implementation of using it.
Consider the basic CDDL that is used as an example on the AJAX homepage (http://www.asp.net/AJAX/AjaxControlToolkit/Samples/CascadingDropDown/CascadingDropDown.aspx)
I duplicated the project and added a twist – the values in the CDDLs are bound to another class. I called this class CarOrder. This CarOrder class has the following interface/implementation:
public class CarOrder
{
public int MakeId { get; set; }
public int ModelId { get; set; }
public int ColorId { get; set; }
}
Instanceses of CarOrders are served by a Factory class like so:
public CarOrder GetCarOrder()
{
CarOrder carOrder = new CarOrder();
carOrder.ColorId = 0;
carOrder.MakeId = 0;
carOrder.ModelId = 0;
return carOrder;
}
public void UpdateCarOrder(CarOrder carOrder)
{
}
The actual implementation of the factory is not germane for this blog so I left it out. Once I get better at Mocking, I can provide a more detailed example.
I then added a Default page to my project and constructed it as so:
The FormView’s Update Panel looks like so:
<asp:DropDownList ID="DropDownListMake" runat="server" Height="16px"
Width="211px" SelectedValue=’<%# Bind("MakeId") %>‘
DataSourceID="ObjectDataSourceCarOrder" DataTextField="MakeId"
DataValueField="MakeId">
</asp:DropDownList>
<cc1:CascadingDropDown ID="DropDownListMake_CascadingDropDown" runat="server"
Category="Make" Enabled="True" PromptText="Select Make"
ServiceMethod="GetMakes" TargetControlID="DropDownListMake"
UseContextKey="True">
</cc1:CascadingDropDown>
Note that the data binding is with the DropDownList. When I run the page, I get the following error:
‘DropDownListMake’ has a SelectedValue which is invalid because it does not exist in the list of items.
Parameter name: value
So Then I put the SelectedValue to the CascadingDropDown like so:
<asp:DropDownList ID="DropDownListMake" runat="server" Height="16px"
Width="211px">
</asp:DropDownList>
<cc1:CascadingDropDown ID="DropDownListMake_CascadingDropDown" runat="server"
Category="Make" Enabled="True" PromptText="Select Make"
ServiceMethod="GetMakes" TargetControlID="DropDownListMake"
SelectedValue=’<%# Bind("MakeId") %>‘ UseContextKey="True">
</cc1:CascadingDropDown>
And things ran like a champ
Some things to remember:
-
Disable EventValidation On the page (or master page if you are using one)
-
If you are using a method from the code-behind, make sure your script manager has EnablePageMethod set to true
-
Make sure your method matches the definition AND
-
If it is a code-behind, make sure the method is marked as static and you use both of these attributes:
[WebMethod]
[ScriptMethod]