Monday, 18 July 2011

Determine Current Page Name with ASP.NET 4.0 and C#


This tutorial will demonstrate how you can easily determine the name of the current page you are on dynamically using ASP.NET 4.0 and C#.

Determine Page Name Dynamically
In certain scenarios you may need to quickly determine the name of the current page you are working with dynamically. To demonstrate this with C#, we will create a simple web site with a web form and display the name of that form on the web page. At this point I have created a new ASP.NET Empty Web Site. To begin:
  1. Right click the project in your solution explorer.
  2. Select add new item...
  3. Select a web form.
  4. Name it 'Default.aspx'.
  5. Click add.
We stand behind Server Intellect and their support team. They offer dedicated servers , and they are now offering cloud hosting

Next, we need to add some simple code to grab the current page name and display it. To do this:
  1. Open Default.aspx.cs up for editing.
  2. Add the following using statement at the top of the class:
    using System.IO;
  3. Add the following code to the Page_Load event method:
    protected void Page_Load(object sender, EventArgs e)
    {
        //get the current page name
        string pageName = Path.GetFileNameWithoutExtension(Request.Path);
        //display current page name
        Response.Write(pageName);
    }
Let's review what this code is doing. We create a variable called pageName, and then call the GetFileNameWithoutExtension method passing it the current path using Request.Path. This returns to us the name of the current file without an extension.

Yes, it is possible to find a good web host. Sometimes it takes a while to find one you are comfortable with. After trying several, we went with Server Intellect and have been very happy thus far. They are by far the most professional, customer service friendly and technically knowledgeable host we've found so far.

Testing
To test this out, load up the web site. Ensure that the correct name of the current page is being displayed without an extension.

No comments:

Post a Comment