Search code examples
c#asp.netevent-driven-designcentralized

How can I handle all my errors/messages in one place on an Asp.Net page?


I'm looking for some guidance here.

On my site I put things in Web user controls. For example, I will have a NewsItem Control, an Article Control, a ContactForm control.

These will appear in various places on my site.

What I'm looking for is a way for these controls to pass messages up to the Page that they exist on.

I don't want to tightly couple them, so I think I will have to do this with Events/Delegates. I'm a little unclear as to how I would implement this, though.

A couple of examples:

1

A contact form is submitted. After it's submitted, instead of replacing itself with a "Your mail has been sent" which limits the placement of that message, I'd like to just notify the page that the control is on with a Status message and perhaps a suggested behaviour. So, a message would include the text to render as well as an enum like DisplayAs.Popup or DisplayAs.Success

2

An Article Control queries the database for an Article object. Database returns an Exception. Custom Exception is passed to the page along with the DisplayAs.Error enum. The page handles this error and displays it wherever the errors go.

I'm trying to accomplish something similar to the ValidationSummary Control, except that I want the page to be able to display the messages as the enum feels fit.

Again, I don't want to tightly bind or rely a control existing on the Page. I want the controls to raise these events, but the page can ignore them if it wants.

Am I going about this the right way?

I'd love a code sample just to get me started.

I know this is a more involved question, so I'll wait longer before voting/choosing the answers.


Solution

  • You can bubble up the event occurs in child to parent page. Parent page can register that event and utilizes it (if it is useful).

    Parent ASPX

    <uc1:ChildControl runat="server" ID="cc1" OnSomeEvent="cc1_SomeEvent" />
    

    Parent c#

    protected void cc1_SomeEvent(object sender, EventArgs e)
    {
        // Handler event
    }
    

    Child C#

    public event EventHandler OnSomeEvent;
    
    protected void ErrorOccurInControl()
    {
         if (this.OnSomeEvent != null)
         {
              this.OnSomeEvent(this, new EventArgs());
         }
    }
    
    protected override void OnLoad(EventArgs e)
    {
         ErrorOccurInControl();
    }