How to set Page's Title from a web content page in ASP.NET 3.5

为君一笑 提交于 2019-12-03 12:34:49

So what needs to happen is this

MasterPage.Master

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
    Me.Page.Title = "Dynamically set in Master page"
End Sub

Default.aspx

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    Me.Page.Title = "Dynamically set in ASPX page"
End Sub

This way your master page title is set BEFORE your content page title. If you do not set a title from the content page, the masterpage will be the default title. If you do set a title from the content page, then it will override it.

The problem is that the Page_Load method in the page runs before the Page_Load method in the user controls in the page, and a master page is actually a user control.

You can use the Page_Init method in the master page instead.

You have to remember that the MasterPage is a child control of the Page, so the OnLoad event fires after the Page's OnLoad event.

In your scenario/example, the page would set the title, then the masterpage would set it again afterwards. Either set it later in the lifecycle or wrap some more logic around who sets it perhaps?

Scott Allen has a good article on this for Master Page's specifically, give it a quick read to get a feel for the lifecycle order.

more simple solution in Master page <%: Page.Title %> - the main title goes here

in content page first line of it <%@ Page Title="Your Title" Language="C#" MasterPageFile="~/_masterpages/... etc

I was having this problem as well. I can't edit the master file (too many possible side effects), so I used the pages PreRender() method, which fires after the master pages Page_Load()

protected void Page_PreRender(object sender, EventArgs e)
{
    Page.Title = Page.Title + " - server error 500";
}

another solution i used sometimes is to put a contentplaceholder in between the title tags on the master page, then you could use a label control in content tag and render it to that.

that way you can give the page a title after controls have posted back, for instance.

to combine Page Title with your Default MasterPage Title you can use the standard template which default ASP.NET web app template uses.

<head runat="server">
    <title > <%: Page.Title %> | Portal Main site Name </title>

this ways this page.Title is read form individual pages

<%@ Page Title="Virtual Machines" ...>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!