In this article I will explain with an example, how to get Current Page and Previous Page names when using Master Page in ASP.Net using C# and VB.Net.
This article will illustrate how to extract Current Page and Previous Page names from URL when using Master Page using the Request.Url and Request.UrlReferrer properties in ASP.Net.
Get Current Page name inside Master Page in ASP.Net
The Request.Url property contains all the information about the Current Page.
The Request.Url.Segments property is an Array built by splitting the Current Page URL by Slash (/) character i.e. Segments of the URL.
The last element of the Array of Segments contains the name of the Current Page.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//Get the Current Page Name.
string currentPageName = Request.Url.Segments[Request.Url.Segments.Length - 1];
Response.Write("Current Page: " + currentPageName);
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
'Get the Current Page Name.
Dim currentPageName As String = Request.Url.Segments((Request.Url.Segments.Length - 1))
Response.Write(("Current Page: " + currentPageName))
End If
End Sub
Get Previous Page name inside Master Page in ASP.Net
The Request.UrlReferrer property contains all the information about the Previous Page.
And similar to Request.Url.Segments property, the Request.UrlReferrer.Segments property is an Array built by splitting the Previous Page URL by Slash (/) character i.e. Segments of the URL.
The last element of the Array of Segments contains the name of the Previous Page.
Note: The Request.UrlReferrer property is NULL if there is no Previous Page and hence it is recommended to make use of NULL checking to avoid exceptions.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
//Get the Current Page Name.
string currentPageName = Request.Url.Segments[Request.Url.Segments.Length - 1];
Response.Write("Current Page: " + currentPageName);
Response.Write("<br />");
//Get the Previous Page Name.
if (Request.UrlReferrer != null)
{
string previousPageName = Request.UrlReferrer.Segments[Request.UrlReferrer.Segments.Length - 1];
Response.Write("Previous Page: " + previousPageName);
}
}
}
VB.Net
Protected Sub Page_Load(ByVal sender As Object, ByVal e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
'Get the Current Page Name.
Dim currentPageName As String = Request.Url.Segments((Request.Url.Segments.Length - 1))
Response.Write(("Current Page: " & currentPageName))
Response.Write("<br />")
'Get the Previous Page Name.
If (Not (Request.UrlReferrer) Is Nothing) Then
Dim previousPageName As String = Request.UrlReferrer.Segments((Request.UrlReferrer.Segments.Length - 1))
Response.Write(("Previous Page: " & previousPageName))
End If
End If
End Sub
Screenshot
Demo
Downloads