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

生来就可爱ヽ(ⅴ<●) 提交于 2019-12-22 17:54:28

问题


How do I reference a master page from an ASP.NET webform? The following statement does not work:

this.MasterPage.Page.Title = "My Title";

回答1:


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";



回答2:


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



回答3:


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'.




回答4:


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;



回答5:


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.



来源:https://stackoverflow.com/questions/917653/how-do-i-reference-a-master-page-from-an-aspx-page

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