ASP.NET 2.0 Client Validation Javascript Bug

comments edit

Bug I recently ran into a perplexing problem that I believe is a bug in ASP.NET 2.0.

Subtext dynamically loads UserControls into the page when fulfilling a request. When commenting on a post, we load a user control that contains the comment form fields and some instances of the RequiredFieldValidator validation control.

While testing, I noticed I kept getting javascript errors when trying to post a comment. Here is the error message:

missing ; before statement

Viewing the source, I noticed the error occurs in the javascript generated by the ASP.NET runtime for client side validation. Here is a tiny snippet of the line with the problem.

var ControlWithValidators.ascx_validateThat = document.all ? ...

Notice the problem? There is a dot in the variable name that Javascript does not like since ControlWithValidators is not an object. What the?

After some digging around I found the culprit. I won’t bore you with the nitty gritty details. When dynamically adding controls to a page, it is a good idea to specify an id before adding them to the Controls collection. That way the controls can reload their state on Postback. However the snippet of code I found was giving the controls an ID that contained a period.

To prove this was indeed the culprit, I created a new simple VS.NET 2005 Web Application Project that exhibits the bug. The page dynamically loads a user control that contains a validation control. Here is the Page_Load method of the web page. When you compile this and run the page, you will see the javascript error.

protected void Page_Load(object sender, EventArgs e)
{
    Control control = LoadControl("ControlWithValidators.ascx");
    control.ID = "ControlWithValidators.ascx";
    placeholder.Controls.Add(control);
}

The quick fix was to simply replace the period with an underscore when assigning the id. Hopefully this helps you if you ever run into something so obscure.

If you are interested in duplicating the bug, you can download the validator bug demo solution here. By the way, does anyone know where is the best place to report this kind of thing?

Comments