Working with the page title in ASP.NET

Tweet

Recently, I’ve had a chance to work with ASP.NET 2.0 a bit, but I still don’t have a business reason to really dive in. One thing I have noticed with the next version is more access to page elements. One particular feature is access to a page’s title, so it can easily be changed in code. I’ve often wanted to do this and I usually utilize pass-thru code to accomplish something dynamic.

Thankfully, it can be accomplished in the current version of ASP.NET. It is easy enough by setting the page title tag as a server control (i.e. with a
runat=”server”) and utilize the following in your codebehind or on the page:


Protected pageTitle As System.Web.UI.HtmlControls.HtmlGenericControl
Private Sub Page_Load(ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
pageTitle.InnerText = "Title"
End Sub

This is VB.NET but it is easily translated to C#.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

  • chris ward

    this has always been available in .net for c#

    like so…


    protected System.Web.UI.HtmlControls.HtmlGenericControl pageTitle;

    private void Page_Load(object sender, System.EventArgs e)
    {
    pageTitle.InnerText = "hello world";

    }

  • Ben

    I haven’t touched ASP.NET 2 yet but I just throw a literal in when I want the title to be dynamic anyway …

  • chris ward

    it’s not a bad idea ben, but you can perform the same in ASP.NET 1, with just a simple

    anything goes here

    works for vbscript.net and c#.net i believe

  • http://www.cynicaldoctor.com/cynicalblog/index.php chadha

    anything goes here
    Works in C# and VB. However, VS.NET 2003 has a bug. When you have typed the above code in the HTML view and you switch to the designer view the IDE removes the runat=”server” tag and you end up getting the object null reference exception when you compile and run the page. The workaround is to swith to design mode after inserting the tag in HTML mode (This causes the web form designer to add a reference to the title tag in the code behind), compile the project and then switch back to HTML and make sure that the runat=”server” of the Title tag has not been removed.

  • Johnny

    Simply using Page.Title = “anything” will do.

  • clintonG

    Using the literal control is the only reliable means to avoid Visual Studio.NET mangling the HTML source.

  • Suneel kumar

    i am new to asp.net i want to remove file menu,asddress bar and statusbar of the browser(IE)
    when running my asp.net page

    my e-mail:suneelkumar_c@yahoo.co.in

  • Drag0nsAng3l

    I am using a “baseform” in which I put all the repeated method that I am going to use in my web app.

    I have the following code in my basepage:

    private String FPageTitle;
    protected System.Web.UI.HtmlControls.HtmlGenericControl pageTitle;

    public String SetPageTitle
    {
    get
    {
    return (FPageTitle);
    }
    set
    {
    FPageTitle = value;

    if (FPageTitle != null)
    {
    pageTitle.InnerHtml = FPageTitle;
    }
    else
    {
    pageTitle.InnerHtml = "";
    }
    }

    The SubPages “inherit” from the base by deriving from
    Purchase.Pages.Base

    Now in my other pages in the PageLoad event i call the following:


    SetPageTitle = "The Title";

    When trying to run the web apps, I get the following error :
    Object reference not set to an instance of an object.

    With the following line highlighted:
    Line 35: pageTitle.InnerHtml = FPageTitle;

    Can someone please tell me what I am doing wrong….
    Thnx in advance.

  • Ant

    Hi Drag0nsAng3l, Not sure if this will help? But if you are trying to access the HTML Title element simply add a ID=”whatever” and a Runat=”Server” to the Title element on the HTML (.aspx) page;

    Once you have done this go to your code-behind file or if you using tags and declare a Protected variable as;

    Protected Title As System.Web.UI.HtmlControls.HtmlGenericControl

    And then in your Button or Page event call the Title variable/element;

    Title.InnerText = “My title”

    As shown here!!! Or you could reverse engineer this by outputting the Title to the page? This is up to you? But I suppose this is worth noting that this kind of idea can be implemented on the body tag as well… just an idea???

    I hope this helps.

  • parveen

    sir
    im a fresher just completed BE in INFORMATION TECHNOLOGYand iwant to know from u that weather i go in the J2EE or .net and plz tell me their scope.Is certification of these technolgies is right for me as im just fresher.

    Regds
    Parveen

  • Ant

    Hi Parveen
    The choice is completely yours… I mean whichever technology you choose!!! This is something you should ask yourself!!! I have never really played with J2EE so I could not comment! Anyway I read an article not long back which may help you in your decision???

    Titled: Microsoft .NET vs. J2EE: How Do They Stack Up?
    Check out this link: http://java.oreilly.com/news/farley_0800.html

    Happy reading :)

  • Paul Smith

    Sick of being burned by the IDE stripping the runat attribute, in VB.net I’ve found the following workaround that’s easier to manage. [One caution: putting code blocks in the .aspx outside the tag screws up the ability to use Page.Controls.Add(). To prevent this from being an issue, just switch to calling .Controls.Add() on the asp:form control instead.]

    In the codebehind (or some global spot if you want to create some centralized title-generating logic):

    Public Shared Function GetTitle(ByVal Page As System.Web.UI.Page) As String
    Dim sSite As String = GetSiteName(Page)
    Dim sPage As String = GetPageTitle(Page)
    Return String.Format("{0} | {1}", sSite, sPage)
    End Function

    Friend Shared Function GetSiteName(ByRef Page As System.Web.UI.Page) As String
    Return Page.Request.Url.Host.ToUpper & " Web"
    End Function

    Friend Shared Function GetPageTitle(ByRef Page As System.Web.UI.Page) As String
    'In reality, you'd do a filename:title lookup, e.g. from Web.config...
    Dim fi As IO.FileInfo
    fi = New IO.FileInfo(Page.Server.MapPath(Page.Request.ServerVariables("SCRIPT_NAME")))
    Dim sTitle As String = System.IO.Path.GetFileNameWithoutExtension(fi.ToString)
    fi = Nothing
    Return sTitle
    End Function

    Then in the .aspx HTML view, no attributes on title are needed:

    ...

  • Paul Smith

    (Apologies for the semi-duplicate post; my 1st attempt lost its formatting, mods please delete…)

    To keep the IDE from stripping the title’s runat attribute, the following workaround does the trick. [One caution: this uses a code block outside the asp-form tag of the .aspx. This screws up the ability to use Page.Controls.Add(), so if you are, call .Controls.Add() on the asp:form control instead.] Now for the

    In the codebehind, or Global.asax.vb, or wherever you want to centralize the title-generating logic:

    Public Shared Function GetTitle(ByVal Page As System.Web.UI.Page) As String
    Dim sSite As String = GetSiteName(Page)
    Dim sPage As String = GetPageTitle(Page)
    Return String.Format("{0} | {1}", sSite, sPage)
    End Function

    Friend Shared Function GetSiteName(ByRef Page As System.Web.UI.Page) As String
    Return Page.Request.Url.Host.ToUpper & " Web"
    End Function

    Friend Shared Function GetPageTitle(ByRef Page As System.Web.UI.Page) As String
    'In reality, you'd do a filename:title lookup, e.g. from Web.config...
    Dim fi As IO.FileInfo
    fi = New IO.FileInfo(Page.Server.MapPath(Page.Request.ServerVariables("SCRIPT_NAME")))
    Dim sTitle As String = System.IO.Path.GetFileNameWithoutExtension(fi.ToString)
    fi = Nothing
    Return sTitle
    End Function

    Then in the .aspx HTML view, you don’t need the runat attribute on the title element; just insert a code block, which the Designer won’t mess with:

    <title><%=GetTitle(Me)%></title>

    Cheers!

  • Juba

    I tried the first option and didn’t work at all… I think the second is way too complicated… So, I worked on a simpler solution:

    At the HTML Title tag:

    At the code behing declare the myTitleVariable as Public:
    Public myTitleVariable As String

    At the Page_Load event:
    myTitleVariable = "Here's my title!"

    Cheers!

  • MR

    Hi,
    I have tried several dynamic page title options, and they wrok fine as long as I have a static page. I mean, when I try to open a pdf file with the following code

    Response.ContentType = “application/pdf”
    Response.BinaryWrite(MyData)
    Response.Flush()

    and then try to change the page title, it does not seem to work. However, without the above code with just a simple aspx page, the page title works. Can someone help me out and tell me how to change the page title with the above code as well. Any help will be appreciated.

    Thanks

  • Anonymous