views:

320

answers:

3

Hello,

I'm building form validation controls for our C# ASP application. The bulk of the work is handled by a BaseValidator control (subclassing System.Web.UI.UserControl), which also has the markup for the validation output. This is then extended by subcontrols like PasswordValidator, that provides the Validate method and any extra fields needed by that validator control.

(The end goal is to have controls like <uc1:PasswordValidator ControlId="txtPassword" /> which we can plop into any form with minimum duplication.)

However, PasswordValidator.ascx.cs cannot access the form elements defined in BaseValidator.ascx; the only way I've found to do so is to duplicate the markup in each subcontrol's *.ascx file. How can I extend BaseValidator.ascx.cs and access BaseValidator.ascx's markup in the subclass?

A: 

I'm pretty sure you'll have to create Server Controls to accomplish this. Meaning, you'll need to generate the outputted Markup from code in the control rather than in the .ascx file.

Shawn Steward
A: 

If you have a true baseclass for your BaseValidator control which your PasswordValidator extends, then any markup/controls in the baseclass should be available through protected properties. I would even go so far as to argue that a true base should not have an ascx portion. The base class should provide methods and properties that expose controls to built on the fly (probably during Page_Init to maintain viewstate).

If you have 2 separate controls on the same page, your parent page can be modified to provide brokerage methods to allow such communication.

If you have the PasswordValidator and you just need the controls/markup, you can use the LoadControl method to create an instance of the BaseControl in memory, access its controls/markup programmatically and either add it or destroy it depending on what you want to do with it.

Barring any of that, it would be just as @Shawn said. Server controls.

Joel Etherton
A: 

Thanks for the suggestions.

I solved this using a service and the strategy pattern. There is a central FieldValidator class which provides validation for any user interface. For the web interface, these methods are exposed through a WebService and (through the WebService) a UserControl. There are no issues with accessing the page elements, because there is now only one UserControl class that stands between the form and the WebService.

For example, <uc1:FieldValidator ControlType="Password" ControlToValidate="txtPassword" runat="server" > will plop down fully-functional clientside and serverside validation, with no need for code behind. Great! :)

(I mentioned resolution a while back in a reply to my question, but I can't mark that as answered.)

Pathoschild