Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Validating an ASP.NET user control from its parent page

I have an asp.net page with a button. This button generates and inserts a user control into the page, so many controls could exist on one page. I need to validate that a certain dynamically generated control inside the generated control exists.

So..Page has 0 to N Control1’s. Each Control 1 can have 0 to N Control2’s. When SaveButton is clicked on Page, I need to make sure there are at least 1 Control2’s inside every Control1.

I’m currently between two options:

• Dynamically insert CustomValidators for each control that is generated, each of which would validate one Control1.

• Do the validation manually (with jQuery), calling a validation function from SaveButton.OnClientClick.

Both are sloppy in their own way – which is why I’m sharing this with you all. Am I missing the easy solution?

Thanks in advance.. (btw – anything up to and including .NET 3.5 SP1 is fair game)

like image 262
JoeB Avatar asked Nov 01 '08 00:11

JoeB


2 Answers

Hmm i like the Interface idea suggested by digiguru but i would use the interface on the container Control1 instead of the sub controls as it seems like the more logical place for the code to live. Heres my take on it:

public interface IValidatableControl
{
    bool IsValidControl();    
}

then implement this on your Control1

public class Control1 : IValidatableControl
{
... Other methods
    public bool IsValidControl()
    {

        foreach(object c in this.Controls)
        {
            if(c.GetType() == "Control2")
                return true;
        }
        return false;
    }

}

There are probably better ways to write this but it should give you enough of an idea to get started.

like image 90
SecretDeveloper Avatar answered Sep 20 '22 20:09

SecretDeveloper


If you are adding user controls on the fly, you could make each control implement the same interface with a Validate function. That way you can load the controls into a placeholder in each parent control on the page. When the page is submitted, simply loop through the controls in the placeholder, cast them to the interface class and then call the validate function. I doesn't use custom validators, but you can build up a list of validation errors using the object returned from the validate function, you can render this collection of validation errors whichever way you like.

like image 28
digiguru Avatar answered Sep 16 '22 20:09

digiguru