How do I reference a master page from an aspx page?

喜你入骨 提交于 2019-12-06 04:32:13

In your aspx, below the Page directive, write:

<%@ MasterType VirtualPath="YourMasterFile" %>

And then from your code, write Master. anything that you want to use, for example:

Master.Title = "My Title";

you have to cast this.MasterPage into the type of masterpage you have, and then you can access it as you'd expect

var mp = this.MasterPage as MyMasterPageType;
mp.Property = value... etc

From the Page you can use the Master property and cast this to your master page. i.e. (MyMasterPage)this.Master. However, whenever I attempt to do this I always check it can be cast first so I normally end up with something like...

MyMasterPage master;
if (this.Master is MyMasterPage)
{
    master = (MyMasterPage)this.Master
    //do stuff with master.
}

If all you are wanting to do is change the title then you can just use Page.Title and make sure that the head tag in your master page is set to runat='server'.

In your code write :

Dim masterpage As New MasterPage
    masterpage = CType(masterpage, MasterPage)

and in your source code where the language is defined and etc type this

MasterPageFile="~/MasterPage.master"

If you write in C#

 MasterPage masterpage = new MasterPage();
masterpage = (MasterPage)masterpage;

In your initial question (before it was edited) I think you mentioned "global settings". Depending on what you want to do, you may want to look into the BasePage concept as well, since I think it might be more suitable. Since you derive from it, all its members are accessible in your code-behind.

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