Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I add a title suffix in ASP.NET (Web Forms)?

Tags:

c#

asp.net

title

I'm trying to add a title suffix = eg " - MySite" to all page titles, but I want to add this in a central location - not manually on each of the pages. How can I do this, as if you have head runat="server" you pretty much lose all control over how this gets rendered.

Currently the titles are set in the Page directive (with the element set to runat="server").

like image 324
NickG Avatar asked Dec 26 '22 14:12

NickG


1 Answers

Could be done with custom PageAdapter. Does not require master pages or editing all page files:

Add adapter class to web project:

using System;
using System.Web.UI.Adapters;

namespace SampleWebApplication
{
    public class PageTitleAdapter : PageAdapter
    {
        protected override void OnPreRender(EventArgs e)
        {
            base.OnPreRender(e);

            if (this.Page.Title != null)
            {
               this.Page.Title = "Somesite - " + this.Page.Title;
            }
        }
    }
}

Right Click on ASP.NET Project/Add/Add ASP.NET Folder, choose App_Browsers.

Add/New Browser File named BrowserFile.browser to that folder.

Edit the file to specify adapter class:

<browsers>
    <browser refID="Default">
        <controlAdapters>
            <adapter
              controlType="System.Web.UI.Page"
              adapterType="SampleWebApplication.PageTitleAdapter">
            </adapter>
        </controlAdapters>
    </browser>
</browsers>
like image 109
PashaPash Avatar answered Dec 30 '22 13:12

PashaPash