Quantcast
Channel: Coded - Web Development and Programming Blog
Viewing all articles
Browse latest Browse all 9

Automatically adding ValidatorCalloutExtenders to your validators

$
0
0

I recently had to work on a pretty big ASP.NET page with lots of fields that needed to be validated.

requiredfieldvalidator.png We thought it would be cool if we used the AJAX Toolkit ValidatorCalloutExtender control on the validators to keep the validation inline and concise.

To quote from the AJAX Toolkit page:

ValidatorCallout is an ASP.NET AJAX extender that enhances the functionality of existing ASP.NET validators. To use this control, add an input field and a validator control as you normally would. Then add the ValidatorCallout and set its TargetControlID property to reference the validator control.

Because we had over 30 text fields, it would have been really tiresome to add extenders manually to each of the validators. So a way to attach them dynamically was needed.

Fortunately, this is pretty easy to do by iterating through the Page.Validators collection, dynamically creating ValidatorCalloutExtender controls and adding them to the Page.

Challenges

  • The first problem I had was an error that occured when trying to dynamically add controls to the Page.Controls collection:

    The Controls collection cannot be modified because the control contains code blocks (i.e. <% ... %>).

    The error probably occurred because of the way I had the MasterPage set up. The solution, although more of a hack, was to add a PlaceHolder to the page and add my controls to it instead of the Page.Controls collection. I named it ValidatorsPlaceHolder (see below)

  • Another problem was that the extender was being dynamically added to a different naming container than the target control, so it wouldn’t find it.

    This lead to the following error:

    Target control with ID 'XYZ' could not be found for extender...

    The error is described in the AJAX Control Toolkit FAQ and the solution is to handle the ResolveControlID event and help it find the control it needs.

    For this to work I needed to create an Extension method for the Page class that would find a control by ID by looking recursively through all of its children.

    Here it is below:

    Usage: var myControl = Page.FindControlRecursive("MyControlsName1");

    Now that this we got this out of the way, here’s the full code listing for the method that adds ValidatorCalloutExtenders to all of the validators.

    Code Listing

    Notice the .ResolveControlID event handler written as a lambda. It uses the FindControlRecursive extension method shown above to help the Extender find the target control, because it will not be able to do it by itself.


Viewing all articles
Browse latest Browse all 9

Latest Images

Trending Articles





Latest Images