I have Cascading Dropdowns, populated via jquery ajax. Follow the link to get the sample code开发者_StackOverflow社区 Download Sample Code
Steps that results into an exception:
1: Make selection for ModelYear, Make and Model
2: Click "Clear button" to reset the dropdowns and that's when it throws an exception.
How can I get rid of this error? I have a weird way to circumvent it by setting hiddenfield upon Clear click and what not, but I will have lot many other controls on page that will do a postback and the workaround I have is getting clumsy and I am looking for a real solution.
May be I am doing something wrong but any pointers welcome.
I have made some access changes to the link. Please try and let me know if that works.
Edit: The sample is developed using VS2005 / .NET 2.0 and WinXP but server will be Win2003.
I've checked your code and I think a fast and easy fix would be to check if the request comes from the clear button. Basically I wouldn't call ReloadDropDownSelection() if you've pressed the clear button.
public partial class CascadingUC : System.Web.UI.UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
ModelYears.Attributes.Add("onchange", "OnModelYearChange()");
Makes.Attributes.Add("onchange", "OnMakeChange()");
Models.Attributes.Add("onchange", "OnModelChange()");
LoadMakes();
LoadModels();
}
else
{
if ((Request.Form["btnClear"]==null)||(Request.Form["btnClear"] != "Clear"))
ReloadDropDownSelection();
}
}
As I told you in my comments I think the problem here is the viewstate. You load your combo server-side (PopulateDropDownList) and then change the items client-side.
I spent a few years struggling with these stuff (asp.net, viewstate, thousands of events) and when ASP.NET MVC came out I've seen the light ;-) I've really really hated ASP.NET webforms. I think it was almost a joke.
I used the workaround of HiddenField to decide if the dropdown should be reloaded upon postback or not. Upon button click I set hidden field value.
Edited: Another way I found to circumvent the error was to enclose my DropDown Databind inside a try block and have an empty catch.
try
{
ddl.DataSource = list;
ddl.DataTextField = "Text";
ddl.DataValueField = "Value";
ddl.DataBind();
}
catch{}
I haven't seen any side-effect of this as far as my code is concerned.
Note: It isn't a good idea all the time to have an empty catch block which will swallow the errors.
精彩评论