I'm writing code on the master page, and I need to know which child (content) page is being displayed. How can I do this programmatically?
Page.Request.Url.PathAndQuery or one of the other properties of the Url Uri object should be available to you from the master page code.
I do something similar to this in a project of mine to dynamically attach css files based on the page being loaded. I just get the name of the file from the request:
this.Request.Url.AbsolutePath
And then extract the file name from there. I'm not sure if this will work if you are doing URL re-writes though.
I don't see an easy way to reference a child page (there is no MasterPage.Child
opposite Page.Master
) though you could add one and have a base Page
class cast its Master
property as your Master
instance and set a Child
property you'd have to create on your Master
page to itself during an OnInit
override.
I found an article that talks about communicating from a Master Page to a regular Page programmatically that may help (jump to "Master Page To Content Page Interaction").
This sounds like a bad idea to start with. The idea of the master is that it shouldn't care what page is there as this is all common code for each page.
You can check the page type in the code-behind:
// Assuming MyPage1, MyPage2, and MyPage3 are the class names in your aspx.cs files:
if (this.Page is MyPage1)
{
// do MyPage1 specific stuff
}
else if (this.Page is MyPage2)
{
// do MyPage2 specific stuff
}
else if (this.Page is MyPage3)
{
// do MyPage3 specific stuff
}
It's better to let the ContentPage
notify the MasterPage
. That's why the ContentPage
has a Master
Property and MasterPage
does not have Child
property.
Best pratice in this is to define a property or method on the MasterPage
and use this through the Master
property of the ContentPage
.
If you use this technique it's best to explicitly specify the classname for the MasterPage. This makes to use the MasterPage in the ContentPage.
Example:
//Page_Load
MyMaster m = (MyMaster)this.Master;
m.TellMasterWhoIAm(this);
Hope this helps.
I use this:
string pageName = this.ContentPlaceHolder1.Page.GetType().FullName;
It retuns the class name in this format "ASP.default_aspx", but I find that easy to parse for most purposes.
Hope that helps!
I have had a reason to check the child page in the master page.
I have all my menu options on my master page and they need to be disabled if certain system settings are not set up.
If they are not then a message is displayed and the buttons are disabled. As the settings page is a content page from this master page I don't want the message to keep being displayed on all the settings pages.
this code worked for me:
//Only show the message if on the dashboard (first page after login)
if (this.ContentPlaceHolder1.Page is Dashboard)
{
//Show modal message box
mmb.Show("Warning Message");
}