ASP.NET MasterPages and User Defined Events
Master pages were introduced in ASP.NET 2.0 and are a great way to create a consistent layout for the pages throughout your application. I thought a good article would be to demonstrate how to create a custom event that web content pages can raise if they click on web server controls located in the master page. If you want to raise an event and pass data to an event handler, you need to create a class that inherits from System.EventArgs . EventsArgs is the base class for classes containing event data. It contains no event data. It is used by events to pass data to an event handler when an event is raised.
To begin with open Visual Studio 2008 and choose File > New > Web > ASP.NET Web Application. Add a master page to the project and name it Site.Master. Before going any further add a new class to the project and name it CustomArgs. Add the following code to the newly created class:
C#
public class CustomArgs : EventArgs
{
public bool Cancel { get; set; }
public string Message { get; set; }
public string NavigateTo { get; set; }
}
VB.NET
Public Class CustomArgs
Inherits EventArgs
Private privateCancel As Boolean
Public Property Cancel() As Boolean
Get
Return privateCancel
End Get
Set(ByVal value As Boolean)
privateCancel = value
End Set
End Property
Private privateMessage As String
Public Property Message() As String
Get
Return privateMessage
End Get
Set(ByVal value As String)
privateMessage = value
End Set
End Property
Private privateNavigateTo As String
Public Property NavigateTo() As String
Get
Return privateNavigateTo
End Get
Set(ByVal value As String)
privateNavigateTo = value
End Set
End Property
End Class
In the code above, CustomArgs inherits EventArgs. This means that when we raise an event in the master page, a reference to CustomArgs will be passed to our event handler, so we can set these properties and have the master page determine what to do next.
Go back to the master page and add the following code to create a new event:
C#
public EventHandler<CustomArgs> ButtonClick;
VB.NET
Public ButtonClick As EventHandler(Of CustomArgs)
We have just created a new event called ButtonClick that accepts CustomArgs as the argument. Now add a Button to the page and add the following code to the Button’s Click event:
C#
protected void Button1_Click(object sender, EventArgs e)
{
lblValue.Text = null;
if (ButtonClick != null)
{
CustomArgs args = new CustomArgs();
ButtonClick(sender, args);
if (args.Cancel)
{
lblValue.Text = args.Message;
}
else
{
Response.Redirect(args.NavigateTo);
}
}
}
VB.NET
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs)
lblValue.Text = Nothing
If ButtonClick IsNot Nothing Then
Dim args As New CustomArgs()
ButtonClick(sender, args)
If args.Cancel Then
lblValue.Text = args.Message
Else
Response.Redirect(args.NavigateTo)
End If
End If
End Sub
What’s happening in the code above is when a user clicks on the Button, which resides in the master page, it will check to see if there’s code that raises the ButtonClick event. If there is, the event handler will be executed. Once the event handler has completed, the master page will check the value of CustomArgs.Cancel property, and if it is false, it will display what is in the CustomArgs.Message property; otherwise it will navigate to the CustomArgs.NavigateTo page.
To see this in action add two web content forms to the project and select the master page added earlier. Leave these pages as WebForm1.aspx and WebForm2.aspx:
To be able to call the event from the master page, you’ll need to add a new MasterType directive to the both pages:
<%@ MasterType VirtualPath="~/Site.Master" %>
This provides a way to create a strongly typed reference to the master page when the master page is accessed from the Master()()() property. Now we must create an event handler for the ButtonClick event. Add the following code to WebForm1.aspx:
C#
protected void Page_Load(object sender, EventArgs e)
{
Master.ButtonClick += new EventHandler<CustomArgs>(MasterButtonClick);
}
private void MasterButtonClick(object sender, CustomArgs e)
{
if (!string.IsNullOrEmpty(TextBox1.Text))
{
e.Cancel = false;
e.NavigateTo = "~/WebForm2.aspx";
}
else
{
e.Cancel = true;
e.Message = "There was no text entered...";
}
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
AddHandler Master.ButtonClick, AddressOf MasterButtonClick
End Sub
Private Sub MasterButtonClick(ByVal sender As Object, ByVal e As CustomArgs)
If (Not String.IsNullOrEmpty(TextBox1.Text)) Then
e.Cancel = False
e.NavigateTo = "~/WebForm2.aspx"
Else
e.Cancel = True
e.Message = "There was no text entered..."
End If
End Sub
In the code above an event handler called MasterButtonClick has been created. This event handler will be raised when the user clicks the Button in the master page. To simulate a business application I’ve added a TextBox to the page so if the user leaves it blank, validation will fail and they should be alerted to this. This is made possible by setting the CustomArgs.Cancel property. If the user does enter data then they will be allowed to navigate to the next page.
Open the WebForm2.aspx page and add the following code to the code behind:
C#
protected void Page_Load(object sender, EventArgs e)
{
Master.ButtonClick = delegate(object s, CustomArgs c)
{
c.Cancel = false;
c.NavigateTo = "~/WebForm1.aspx";
};
}
VB.NET
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs)
Master.ButtonClick = Function(s, c) AnonymousMethod1(s, c)
End Sub
Private Function AnonymousMethod1(ByVal s As Object, ByVal c As CustomArgs) As Boolean
c.Cancel = False
c.NavigateTo = "~/WebForm1.aspx"
Return True
End Function
In the code above I have created an anonymous method that handles the ButtonClick event. This page will not validate anything and therefore will direct the user back to the WebForm1.aspx page.
If you run the application and step through the code you’ll see that when you click on the button in the master page, it will check and execute the event handlers in the web content forms. This is a nice way of being able to create a wizard style application, but having the flexibility of raising events in the child pages when you need to.
The entire source code of this article can be downloaded from here
This article has been editorially reviewed by Suprotim Agarwal.
C# and .NET have been around for a very long time, but their constant growth means there’s always more to learn.
We at DotNetCurry are very excited to announce The Absolutely Awesome Book on C# and .NET. This is a 500 pages concise technical eBook available in PDF, ePub (iPad), and Mobi (Kindle).
Organized around concepts, this Book aims to provide a concise, yet solid foundation in C# and .NET, covering C# 6.0, C# 7.0 and .NET Core, with chapters on the latest .NET Core 3.0, .NET Standard and C# 8.0 (final release) too. Use these concepts to deepen your existing knowledge of C# and .NET, to have a solid grasp of the latest in C# and .NET OR to crack your next .NET Interview.
Click here to Explore the Table of Contents or Download Sample Chapters!
Was this article worth reading? Share it with fellow developers too. Thanks!
Malcolm Sheridan is a Microsoft awarded MVP in ASP.NET, a Telerik Insider and a regular presenter at conferences and user groups throughout Australia and New Zealand. Being an ASP.NET guy, his focus is on web technologies and has been for the past 10 years. He loves working with ASP.NET MVC these days and also loves getting his hands dirty with jQuery and JavaScript. He also writes technical articles on ASP.NET for SitePoint and other various websites. Follow him on twitter @
malcolmsheridan