The MasterPage Article I Thought I’d Never Finish

… because it kept growing and growing. I was determined to finish this off tonight before falling asleep (always dangerous).

Master Pages: Tips, Tricks, and Traps is an article covering all the inconspicuous points of developing and designing with master pages. Everything from URL rebasing, the munging of client side identifiers, using FindControl, nesting, and even tips for cross page posting.

As always, I appreciate any feedback. I’m particularly interested to know if the reader finds the intermingling of Visual Basic and C# samples to be useful, or just a terrible idea.

Now to sleep, perchance to dream...

posted on Wednesday, April 12, 2006 1:09 AM by scott Rated Excellent [5 out of 5].

Comments

Wednesday, April 12, 2006 2:58 AM by James Newton-King - Newtonblog

# Testing if a ContentPlaceHolder is Empty

K. Scott Allen, one of the many Scotts who seem to develop in .NET, has written a comprehensive article...
Wednesday, April 12, 2006 9:25 AM by Peter Kellner

# re: The MasterPage Article I Thought I’d Never Finish

Great Article! I never realized there was so many things to worry about on a Master Page
Wednesday, April 12, 2006 10:51 AM by Jun Meng

# re: The MasterPage Article I Thought I’d Never Finish

Great article! :)

One typo (maybe): "We can visualize what the object hierarchies would look like at runtime with the following diagram." Here you mean "at design time", right?
Wednesday, April 12, 2006 11:27 AM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Jun: that first diagram would be what the objects look like at the very start of the page lifecycle, before Pre_Init and before the master page injects itself. I'll try to edit the article later tonight and make that a bit more clear.
Wednesday, April 12, 2006 7:24 PM by Christopher Steen

# Link Listing - April 12, 2006

"Atlas" April CTP Release [Via: Rich Ersek ]
[T-SQL] Call a stored procedure once for each row in a...
Friday, April 14, 2006 9:55 AM by steve

# re: The MasterPage Article I Thought I’d Never Finish

Outstanding! Thanks.
Tuesday, April 18, 2006 6:45 AM by Eric Golpe <egolpeATgmail.com>

# re: The MasterPage Article I Thought I’d Never Finish

Hi Scott,

Question.. I have a base class in App_Code that extends the UI.Page class, and so I created a .master page, and on the content page, I changed BOTH the Inherits attribute of the aspx to the new extended base class name, AND the class declaration (class Default3 : MyExtendedPageClass) but I get:

"Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl"

Should I NOT change the class declaration?

and one more while I got you interested... Can you use multiple user controls programatically on a Master page itself? (not the content page) and what is the correct way to do it??

I hope you can help me out. Thanks!! GREAT article BTW
Tuesday, April 18, 2006 10:22 AM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Eric:

Make sure you also add the CodeFileBaseClass attribute in your @ Page directive and point it to that base class.

Yes, you can programatically use user controls on a master page. I wouldn't treat the master page any different than a regular Page, all of the same examples apply.
Tuesday, April 18, 2006 2:16 PM by Jon

# re: The MasterPage Article I Thought I’d Never Finish

Hi Scott,

Good Article. I've been fumbling with findcontrol and masterpage's for a while. I decided to use the property get set instead, much cleaner. I'm curious though and forgive me if I missed this or if this is a stupid question but is there a way to expose all of the controls properties as opposed to just the specific property, when you call it?

Thanks,

Jon
Tuesday, April 18, 2006 4:24 PM by Chris

# re: The MasterPage Article I Thought I’d Never Finish

> left at the other Scotts blog. LEft here for the sake of being in the right place. :-)

--
I completely and thourgh;y hate the Name Mangling when using master pages. It makes it damn near impossible... or highly impractical to create sanely named CSS outside of using themes.

This becomes twice as bad when you have developers who do the code, and designers who do the CSS, and you have a predefined Id naming conventions. The Id the designers see in the .aspx source isn't what you get in the output, obviously makeing CSS mistmatch the expectations.

It's why we're not using master pages at all.
Tuesday, April 18, 2006 8:17 PM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Jon:

I can't think of an easy way to expose all of the controls as properties (without writing all the code, that is). Perhaps some sort of macro or VS add-in could do that by generating code.

Chris:

I understand your problem. I guess it is a trade-off the ASP.NET team made (easier for postback resolution, harder for css and javascript). Perhaps it's something they could provide a workaround for in the future.
Wednesday, April 19, 2006 12:15 AM by scottgu@microsoft.com

# re: The MasterPage Article I Thought I’d Never Finish

Chris -- I posted a reply to your comment on my blog post: http://weblogs.asp.net/scottgu/archive/2006/04/18/443276.aspx#FeedBack

Hope this helps,

Scott
Wednesday, April 19, 2006 9:18 AM by Ryan Anderson

# re: The MasterPage Article I Thought I’d Never Finish

Some one give this guy another medal.
Nice, thorough, well thought out.
One of the things I appreciate about your tech writing style is that you just don't say, "this is how you do it..."
You give different examples of how it can be accomplished, and then revisit each scenario and point out the pros and cons of each and expanding on the best direction to go. That style is nothing short of value added!
Many thanks for your continued efforts in contributing to edumacation of us knuckleheads out here! :)
Wednesday, April 19, 2006 9:23 AM by Paulo Aboim Pinto

# Master pages, truques e armadilhas....

Wednesday, April 19, 2006 2:57 PM by Jon

# re: The MasterPage Article I Thought I’d Never Finish

Thanks Scott,

Well even if I can't define the entire control it's still a better solution then working with findcontrol. I was pleased to find out I could issue a Atlas UpdatePanel Update command within the property get set routine to show the new changes, since a have a update panel in my master page. It works like a charm. I agree with Ryan about your tech writting style. Keep up the good work!!!
Thursday, April 20, 2006 6:59 PM by Nisar Khan

# re: The MasterPage Article I Thought I’d Never Finish

Hi Scott,
I have read your great article and i have question for you :) if you can please help me.,
i try to implement you code esp "Master Page To Content Page Interaction"

i have setup as you have described in your web site and i always get "null" value here:

i'm working VS2005:

protected void SendEmailButton_Click(object sender, System.EventArgs e)
{
SendEmailEventArgs eventArgs = new SendEmailEventArgs(this.EmailAddressBox.Text);

if (SendEmail != null) <<always null value
{
SendEmail(this, eventArgs);
}
}


if you want to see the whole page, please let me know and ii can post here or email you whichever is easy for you., hope to hear from you soon.

thanks
Thursday, April 20, 2006 7:45 PM by Nisar Khan

# re: The MasterPage Article I Thought I’d Never Finish

do you have anything related with:

Content Page To Master Page Interaction?

thank you
Friday, April 21, 2006 7:00 AM by Scott Allen

# re: The MasterPage Article I Thought I’d Never Finish

Yes, the article covers interaction in both directions.
Friday, April 21, 2006 7:03 AM by Scott Allen

# re: The MasterPage Article I Thought I’d Never Finish

Nisar:

The event will be null until someone subscribes to the event. Typically the page would subscribe to the event (SendEmail += new SendEmailEventHandler(...))
Friday, April 21, 2006 1:03 PM by Brian

# re: The MasterPage Article I Thought I’d Never Finish

Regarding FindControl,

I find it's behavior so annoying I created a simple routine to find any control within any other control. This uses recursion to return the FIRST control matching the supplied name. If the control is not found it simply returns null, instead of raising an exception. Let me know what you think.


public static Control Find(Control C, String ControlName)
{
if (C.ID == ControlName) return C;

foreach (Control c in C.Controls)
{
Control cntrl = Find(c, ControlName);
if (cntrl != null) return cntrl;
}

return null;
}
Sunday, April 23, 2006 12:26 PM by steve

# re: The MasterPage Article I Thought I’d Never Finish

The last part of your article, "Nesting Master Pages" and "Content controls are allowed only in content page that references a master page" issue, the fix for that really saved me

Thanks!
Tuesday, April 25, 2006 5:59 AM by Atul Reddy

# EXCELLENT Article

Only after reading your article, i realized that there are many work around ways in dealing with 'MasterPage's.

Quick Question-
Any idea on how to create 'Menu round shaped multiline Tabs'in webforms (Asp.net 2.0) similar to 'Tabcontrol' now available in winforms (.net 2.0).
Any available references?

My Email- atulreddy@yahoo.com
Tuesday, April 25, 2006 1:53 PM by Vani

# re: Question on adding controls to master pages

Please let me know how to add server controls/web custom controls/user controls to a master page. In vs 2003 version, we had something like the Tag Prefix - how do I call that tag name and prefix after Registering the tag with name a nd other attributes n vs2005 ?

Thanks
Vani
srivanimk@hotmail.com
Tuesday, April 25, 2006 4:46 PM by Ed

# re: The MasterPage Article I Thought I’d Never Finish

Great article and so helpful. Thanks. I am getting a NullReferenceException: when I try and set the footer text from the content page. Base Class is BaseMaster,
BaseMaster footer = new BaseMaster();
footer.FooterText = "My Footer"; in the contentpage in Page_PreInit, or page load or in a LinkButton1_Click, bombs.
Any idea what I am missing?

I can access and set other properties in the Base Class, no prob but the setting I lifted from your article that starts with
“protected Label FooterLabel;” fails. Thanks again for a great article I will be working on it for a while.

Ed
Wednesday, April 26, 2006 7:17 PM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Ed: You shouldn't have to "new BaseMaster()" if that is the base class for your master page. It's an inheritance relationship.
Friday, April 28, 2006 9:07 AM by Diego Beltran

# UserControls inside the ContentPlaceHolders sitting on Master Pages/Content Pages

Hi Scott,

Your article is very impressive. I have a question though. My case is as follows:
I use a master page which has 4 main ContentPlaceHolders (header, footer, subNavigagion and Main content)

The content pages (child pages of this Master Page) will, at Page_PreRender event load different user controls into this place holders, based on a selected language (up to 7 different languages) and reading from a global resource file (items.resx, items.fr.resx, etc.).

What happens is that the user controls, such as dropdowns or checkboxes, buttons etc… trigger the autoPostBack event but do not go into the actual Click event. For instance: a dropdown will look like this inside the UserControl:
Protected Sub lstAttributeName_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles lstAttributeName.SelectedIndexChanged

End Sub

But at runtime, it goes into the pageLoad event for that UserControl and it NEVER reaches SelectedIndexChanged method.

HOW can I make this dropdown to actually go into this method? I’ve been spinning my wheels on this for a while now.

Please help me if you can.

Much appreciated.

Diego Beltrán
Friday, April 28, 2006 11:13 AM by trevork

# re: The MasterPage Article I Thought I’d Never Finish

A well constructed, useful article - thanks!

You asked for comments about mixing VB and C#?
I have to say, I found it annoying.

Trevor
Monday, May 01, 2006 10:43 PM by Tyler Carver

# re: The MasterPage Article I Thought I’d Never Finish

Hi, awesome article. I have a question about dynamically setting the MasterPageFile on the parent of a nested MasterPage. I can't seem to find a way to do this dynamically. There is no PreInit event for the MasterPage and the Page that is loading has to set the nested page as it's MasterPageFile. It seems there is no way to get to the MasterPageFile property of the parent master page before the OnInit event is called.

Any suggestions? This would be awesome because I could dynamically swap out the MasterPage including the parent of all nested MasterPages.

Thanks,
Tyler
Tuesday, May 02, 2006 1:29 AM by James Spibey

# re: The MasterPage Article I Thought I’d Never Finish

Hi Scott,

Great article - thanks for taking the time to wrote it. I have a particular problem which I don't seem to be able to solve so I was hoping you could offer some insight.

I have a common baseclass called TemplatePage which I use for all my pages which is derived from System.Web.UI.Page. Each page in my site in turn derives from TemplatePage. How can I reference my MasterPage from the TemplatePage class? I get an error at present which states that the master page doesn't exist. I assume that this is because my base class is in the App_Code directory and so the MasterPage class isn't available.

Any advice would be very appreciated
Tuesday, May 02, 2006 6:12 AM by TristanK

# re: The MasterPage Article I Thought I’d Never Finish

Thanks so much for a staggeringly informative article.

I tried to read it all in one go, but my brain popped, almost as if I'd been struck.

I vow to return, and bring my friends, rough it up a bit, and send it on its way with no lunch money.
Tuesday, May 02, 2006 6:22 AM by Scott

# re: The MasterPage Article I Thought I’d Never Finish

Tyler: In the PreInit event handler for the Page you could use Master.MasterPageFile = "...";

James: You've identified the problem. Because App_Code compiles before any .aspx and .master files the base page class won't see any master page types. You could define a base class for your master page, too, and the base page class could talk to the master through that base class (an interface also works).
Tuesday, May 02, 2006 6:24 AM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Thanks, Tristan.
Tuesday, May 02, 2006 8:28 AM by James Spibey

# re: The MasterPage Article I Thought I’d Never Finish

Thanks for the reply Scott. I added a base class to my Master Page and that got me over this hurdle but I've found another one in that our TemplatePage base class uses typeof to figure out which page we are on and performs certain actions based on that. This doesn't work of course in this new website model so we're stuffed again.

We've decided instead to use Web Application Projects instead because of these problems. Thanks again for your help
Tuesday, May 02, 2006 4:10 PM by Dan O

# re: The MasterPage Article I Thought I’d Never Finish

Great article - one of the best asp.net articles I have seen.
Tuesday, May 02, 2006 9:29 PM by Tyler Carver

# re: The MasterPage Article I Thought I’d Never Finish

Scott, thanks for the fast reply. I had been trying to set the MasterPageFile on the nested MasterPage that very way, Master.MasterPageFile =... I now realize that I had created another problem that caused this to fail. It actually does work but I was doing this in my base class to get easy access to the MasterPage in a type safe way:

protected new MyMaster Master
{
get { return (MyMaster)Master; }
}

This had been working great but fails in the nested scenario. I can set the MasterType in the page file but I liked doing this in one spot in the base class for all pages. By the way this caused a nasty stack overflow.
Wednesday, May 03, 2006 7:36 PM by Kevin

# re: The MasterPage Article I Thought I’d Never Finish

Good Article. One thing the master pages doesnt give you is the framestyle layout. there is no way to control postback on different sections of the masterpages and I thik that's their downside.
Thursday, May 04, 2006 11:50 AM by Priya

# re: The MasterPage Article I Thought I’d Never Finish

Good one. I have a custom control with a button. The button click event fires if the page is without master. But, after the master is added, the event does not fire. Can you please help with this? Thanks a lot.

Thursday, May 04, 2006 2:44 PM by matt vaughn

# re: The MasterPage Article I Thought I’d Never Finish

"You hit one out of the park." I'm currently refactoring a base page that is really overloaded with everything from Session, Authentication, control manipulation, and navigation...

Your discussion of using HttpModules to hook into events from an ASP.Net page was very thorough and well organized. I'm a repeat customer to your blog. Keep up the good work.
Thursday, May 04, 2006 7:38 PM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Thanks, Matt.

Pryia: I'd have to see some code. If you could email me a sample that demonstrates the problem, that would work best.
Friday, May 05, 2006 12:19 PM by Priya Raj

# re: The MasterPage Article I Thought I’d Never Finish

Scott, I emailed you the code details.

Thanks,
Priya
Monday, May 08, 2006 10:07 AM by Vik

# re: The MasterPage Article I Thought I’d Never Finish

Scott,
Gr8 article!!! I was just trying to figure out a better way of including JS scripts in content pages, your article helped me in figuring that out & understanding the limitations of master pages.

-Vik

Tuesday, May 16, 2006 3:41 PM by Avi

# re: The MasterPage Article I Thought I’d Never Finish

Hi Scott,

I have been racking my brains out on this for days...

I have added a menu control to a master page. The only issue I have is when you click on menu items which have navigateURL assigned (as in site maps) the page changes to the URL specified, and you can not tell which menu item was clicked.

I had no problem with this when I used LinkButtons for navigation (on every page) since I could always access them from various pages and change their color.

Of course, I only care about this behavior at the static menu level only. I am using a dynamic menu based upon the contents of a SQL SiteMap table.

Any help or suggestions would surely be well appreciated.

Thanks.

P.S. Why do I see no examples of anyone trying to manipulate the menu control on a master page?
Wednesday, May 17, 2006 10:38 PM by J.P.

# re: The MasterPage Article I Thought I’d Never Finish

Scott,

I am having *major* difficulties using the FindControl to access a Button WebControl. I'm using nested master pages, so I've got the following objects I'm working with:

phMain - the ContentPlaceHolderID on my main Master Page, titled ABSOLUTE_main.master
phAdminContent - the ContentPlaceHolderID on my nested Master Page, titled ABSOLUTE_admin.master
btnAdjust - the Button WebControl that resides on my content page

The issue centers around my nested master pages. I did as you mentioned by calling everything out in a single line of code; I used the following (in C#):

WebControl button = (WebControl)Page.Master.FindControl( "phMain" ).FindControl("phAdminContent").FindControl("btnAdjust");

This throws an unhandled NullPointerException, which is on the button "btnAdjust". The button *does* exist, as this line of code (using the hairy munging naming convention) will, in fact, find my button:

WebControl button = (WebControl)Page.FindControl("ctl00$ctl00$phMain$phAdminContent$btnAdjust");

That works...as ugly as it is, but I cannot work this way. I've got other controls that I need to "Find" on the Page, and this guessing game of what the control will ultimately be named is both maddening and impossible.

I decided to simplify my code for grins (try the ol' outward-in trick) by simply seeing what would return from this statement:

ContentPlaceHolder content = (ContentPlaceHolder)Page.Master.FindControl( "phMain" );

Guess what I get??? A null value! Why would I receive a null value on that line of code??? My expectation was to receive an object that I could dissect and eventually work my way into. A null value isn't acceptable.

I decided to go the other way, thinking that maybe the nested master page resolves first, as you suggest in the article. I did the following, by itself:

ContentPlaceHolder content = (ContentPlaceHolder)Page.Master.FindControl( "phAdminContent" );

Any guesses what value came back?? A null. I'm at a serious loss here. What can possibly be going wrong? I can send you anything you need...I'll send it. :)

HELP! :)

I am in an extremely dire situation here. I cannot continue with my project until I get this worked through. Why did I ever attempt to use Master Pages????

Thank you for the article (it was very informative) but it didn't spend enough time on the perils of nested pages. Or, maybe it did, and I just need to stay away from master pages entirely. :)

J.P.
zurilgenj@saic.com
Thursday, May 18, 2006 7:31 AM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Avi: I have not worked with the menu control extensively, sorry.

J.P: That does seem like odd behavior. If you want to send me a sample that compiles and demonstrates the problem and I can probably take a look: scott @ OdeToCode.com.
Friday, May 19, 2006 9:43 AM by J.P.

# re: The MasterPage Article I Thought I’d Never Finish

Scott,

After contemplating hara-kari (j/k), I continued to poke and prod at this problem. I thought back to something you said ("the page will resolve from the inside out"). My nested page (ABSOLUTE_admin.master) would resolve itself and dump all of its constituent controls into its contentplaceholder, then the main master page (ABSOLUTE_main.master) would resolve, and all of the controls from the nested master page would be dumped into the outer-most master page. THEN, the outer-most master page would dump all of ITS controls into the content page....and away I go.

After thinking about this a bit, I wondered what would return if I tried the following code:

Object obj = Page.Master;

Lo and behold, it was a reference to my nested master page (ABSOLUTE_admin.master). This made sense to me, based on what you said about the resolution timing of all elements.

O.k., so I thought a bit....what happens here:

Object obj = Page.Master.MASTER;

And, as expected, I got a reference to the outer-most master page (ABSOLUTE_main.master).

O.k., so now, with all fingers and toes crossed, I tried the following code and prayed and prayed:

WebControl button = (WebControl)Page.Master.MASTER.FindControl( "phMain" ).FindControl("phAdminContent").FindControl("btnAdjust");

And it worked!!! I think the main thing I have to keep in mind when working with nested master pages is that you ALWAYS have to move to the outer-most level...get a reference to the outer-most ContentPlaceHolder first, then drill into it to get what you need. So, in my case, I needed the master OF THE MASTER to begin my search.

And, it makes total sense...you need to start with the FindControl() method at the page level, then drill into each container to get what you are after. I just need to keep in mind that the ContentPlaceHolders in the Master Page environment are the outer-most containers...always. :)

<insert huge sigh of relief> I sincerely thank you for writing this article, articulating the pitfalls of Master Pages. My Professional ASP.NET 2.0 book from WROX is very well-written, but only introduces you to Master Pages. I was able to get my pages working, but the issues I've been facing have been long and difficult. I believe your article will come in handy down the road to side-step these landmines.

Thanks so much!

J.P.
Tuesday, May 23, 2006 6:09 PM by Munir Syed

# re: The MasterPage Article I Thought I’d Never Finish

Hi, Great article and actually very self explantory so well done. It gives me some ideas regarding implementing a framework page. I am looking for more innovative ideas about handling and display page level errors and hooking up masterpage to show business errors using maybe a javascript window(restrictions apply when ie has blocker on!!). Do you have any suggestions about these. I'd be very interested in them. Thanks again, carry on your superb work!
Friday, June 02, 2006 10:31 AM by Steve

# re: The MasterPage Article I Thought I’d Never Finish

Scott -

Great article, and timely too. I will be back. In the article, you mention using a HttpModule to set the Theme for all pages. Couldn't the same be done in the global.asax in the PreRequestHandlerExecute event? This would save having to configure the web.config for the application. Thoughts?

Steve
Friday, June 02, 2006 1:54 PM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Steve:

That's true, it's just I've seen global.asax file grow out of control with little bits of functionality here and there, so proceed with caution :)
Saturday, June 03, 2006 2:57 PM by Gene

# re: The MasterPage Article I Thought I’d Never Finish

Thank you for your work on this article; it helped me a great deal.
Monday, June 05, 2006 10:05 AM by Adam Tibi

# re: The MasterPage Article I Thought I’d Never Finish

Nice article that should be read before any attempt to use a MasterPage.
Consider this code:
MasterPage 1:
<asp:ContentPlaceHolder ID="cphHead" runat="server">
</asp:ContentPlaceHolder>
Some Html...
<asp:ContentPlaceHolder ID="cphBody1" runat="server">
</asp:ContentPlaceHolder>

MasterPage 2:
<asp:ContentPlaceHolder ID="cphHead" runat="server">
</asp:ContentPlaceHolder>
Some Html...
<asp:ContentPlaceHolder ID="cphBody2" runat="server">
</asp:ContentPlaceHolder>

Page:
<asp:Content ID="Content1" ContentPlaceHolderID="cphHead" runat="Server">
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="cphBody1" runat="Server">
</asp:Content>

<asp:Content ID="Content3" ContentPlaceHolderID="cphBody2" runat="Server">
</asp:Content>

This will issue an error saying that the content is pointing to a cph that doesn't exist (which is a logical error). However, I'm building multibranded sites that will need such an approach!

I tried to find ways to catch the error and ignore it, also, tried, in a HttpModule, to find the Content that doesn't have an equivillent CPH to remove it from the page but that didn't work!

The problem is that you can't catch the Content because it doesn't really exist!

Do you have any solution or an alternative approach (not by using IF ELSE) for this problem?

Regards,
Adam
Tuesday, June 06, 2006 2:12 PM by Peter Bromberg

# re: The MasterPage Article I Thought I’d Never Finish

Scott,
Best "Get under the hood" Master-Mechanic article on MasterPages on the net. Good work.
Appreciate it!
Monday, June 12, 2006 6:45 AM by Rich

# re: The MasterPage Article I Thought I’d Never Finish

Great article. Masterpages are what I've been needing ever since I migrated to .net 1.1

Your guide touches on sharing masterpages across multiple apps. Your first suggestion seems the most appropriate although I cannot get it to work. Just a "Masters/Master1.master" file does not exist error. I created the virtual directory for the web app using the masterpage app through the IIS admin. Is that what you meant?

Thanks
Monday, June 12, 2006 9:06 PM by dokmanc

# re: The MasterPage Article I Thought I’d Never Finish

I must admit your article was a bit over my head, I will try a couple more times to reread it.

In the meantime, I would be most grateful if you could answer a question that I posted to a newsgroup by did not receive a satisfactory answer:

http://groups.google.com/group/microsoft.public.dotnet.framework.aspnet/browse_thread/thread/ed128f111e2fc826/eb862a9635f5ad3e?lnk=st&q=I+want+to+pass+a+string+variable+from+default3.aspx+to+default2.aspx&
Friday, June 16, 2006 1:25 AM by Andy Lee

# re: Broken Urls

Good work, one thing you didn't mention regarding the relative urls is when you use them within Javascript files.

The only solution i could think of was to pass the server rootpath into a javascript variable and then use this in the javascript file...

<script language=JavaScript>
var rootPath = '<%= ResolveClientUrl(".") %>' + '/';
</script>

I added this to the MasterPage.
Sunday, June 18, 2006 6:35 AM by John Gillespie

# re: The MasterPage Article I Thought I’d Never Finish

A great article as everyone says.

I have a question for you. I have a master page which takes care of tracking page views etc. I then have a content page which varies based on the query string.
I want to have the code in the master called but cache the page content as neccessary.

I can cache the content of the page in a user control and that is fine. What I can't (yet) do is somehow cache the html header section (ie meta tags for keywords, description, and page title), without caching the WHOLE page.

Right now the first request has the updated header but all subsequent (cached) pages revert to the master page's version of the header.
Do you have any idea how I could fix this?

Thanks

John
Tuesday, June 27, 2006 9:12 PM by Fabiano Arruda

# re: The MasterPage Article I Thought I’d Never Finish

very very very great, i've need this tips these days.

thank you very much

Fabiano Arruda
fabiano.arruda@cesar.org.br
Tuesday, June 27, 2006 10:55 PM by Sukki

# re: The MasterPage Article I Thought I’d Never Finish

Hi Steve,
i am having one master page and 3 content pages are there.In the content page1 i am giving refernce in the aspx page of remaing 2 pages.Its working fine but "The issue is since each page is compiled to a different assembly it does not know the referes and hence cannot reference it." what the next step i had to proceed?
plz clarify ASAP.

thks
Wednesday, June 28, 2006 11:44 PM by Markus

# re: The MasterPage Article I Thought I’d Never Finish

I wish I had read this before putting months of effort into the site I'm building...
Great article, now I actually understand at least a little bit of masterpages!
Thursday, June 29, 2006 6:42 AM by Eric

# Page Directive Approach

Scott,

Meta tags is the only trouble we've had with Master pages, which was an oversight on Microsoft's part. Anyway, I tried to implement as you've outlined in the article, to no avail. Here are my steps:

1) Create a new Class file in App_Code that inherits from Page (I've called this MetaPage)
2) That class contains your code and seems to compile OK
3) I then changed an individual ASPX codebehind page to inherit from that new MetaPage instead of the usual Page; this seems to match what you have as well since it's in the @Page directive

Anyway, once I add in the "MetaKeywords" in the Page directive, it barfs that it's not an attribute of System.Web.UI.Page, even though I'm inheriting from my MetaPage instead. I did not touch the Master file, as your example also did not seem to touch the Master file. Any guidance is appreciated. :-)
Thursday, June 29, 2006 8:10 AM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Eric:

That is the Visual Studio validation being overly zealous.

The project should still compile and run, it's only Visual Studio that complains because it doesn't know about the property.

Let me know,
Friday, June 30, 2006 12:02 PM by Eric

# re: Page Directive Continued

Scott,

No, it neither compiled nor ran. Does the .master also have to inherit from the MetaPage class or just the Page class?

Do you have a working sample project that implements this perchance? I have an alternate solution that doesn't do page directives instead using a Page_Load that calls the Master, but my graphics designers don't do/understand code-behind code, but could deal with page directive codes. They are the ones frequently tagging these, so your solution is the most elegant... if it would work.

Thanks! :-)
Sunday, July 02, 2006 5:16 PM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Eric:

ARe you using code-beside files (CodeFile="")? If so, use a CodeFileBaseClass attribute also. The CodeFileBaseClass attribute will contain the name of your base class. I'll be posting a sample tonight or tommorow, stay tuned.
Wednesday, July 05, 2006 5:35 PM by doWhileSomething

# re: The MasterPage Article I Thought I’d Never Finish

The article was very informative and although it was not exactly what I was looking for - I figured I would post the question.

I need to find out what page has been loaded as a child of the master page.

Reason, I have a few menus that are on the master page which are in panel containers and I only wish to make certain panels visible depending on which pages are selected.

So, I need to check from the master page what child page is active.

Thanks in advance.
Thursday, July 06, 2006 6:03 AM by scott

# re: The MasterPage Article I Thought I’d Never Finish

I'd probably have my web forms derive from an interface or base class that can tell the master page what it needs to know.
Monday, July 10, 2006 8:43 AM by sbyard

# re: The MasterPage Article I Thought I’d Never Finish

To re-inforce what's been mentioned above. There are TWO issues with inclucing Javascript files that contain urls - e.g. you use window.showModalDialog to open an ASPX web page as a dialog.

1 js file location itself has to be resolved in sub-folders
2 url of dialog called in a javascript function requirs resolution

(2) can be resolved as follows in code-behind.
if (!Page.ClientScript.IsStartupScriptRegistered("JavascriptSiteNamePrefix"))
Page.ClientScript.RegisterStartupScript(typeof(Page), "JavascriptSiteNamePrefix", @"<script language='javascript'> var rootPath = '" + Request.ApplicationPath + "/'; </script>");
Monday, July 17, 2006 5:43 AM by JetBrain

# re: The MasterPage Article I Thought I’d Never Finish

Thanks for the article.. but I have a question... I want to make a dynamic menu in the master page.. I mean that the menu change according to the content of the pages in the place holder.. do you have any idea how can that be done?

Thanks in advance
Monday, July 24, 2006 4:31 AM by Zaheer Ahmad

# Excellent!

I am new to ASP.NET. I don't have much experience. This artical helps me a great. Especially the "Handling the PreInit Event" and "Abstract Interaction" parts are great.
Friday, July 28, 2006 2:27 PM by arun

# re: The MasterPage Article I Thought I’d Never Finish

i like this artical because it explain how to fine the controls in the master pages and other important features of the mastser pages
Saturday, July 29, 2006 9:26 AM by Peter Kellner

# re: The MasterPage Article I Thought I’d Never Finish

Hi Scott,

Great article. Two quesitons.

1. any thoughts on how to get a background image into a div tag on a master page? (that works from aspx pages in subdirectories).

2. How to you format your code on your blog?

Thanks! -Peter
Sunday, July 30, 2006 10:33 AM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Hi Peter:

1) I'd set the background image using CSS and keep the image and style sheet in the theme directory.

2) I use Jeff Atwood's code formatting macro: http://www.codinghorror.com/blog/archives/000319.html
Sunday, July 30, 2006 2:59 PM by Peter Kellner

# re: The MasterPage Article I Thought I’d Never Finish

Hi Scott,

I'm not quite understanding what you mean by placing the image in the theme directory. I put the jpg in my directory called "MyProject/App_Themes/ThemeNormal" and made my background in the css this:

<div id="header_image" style="background: transparent url(bg_header.jpg) repeat-x scroll 0% 0%;cursor: pointer;">

I'm still not getting the image.

Sorry for being a little thick.

-Peter
Sunday, July 30, 2006 7:58 PM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Not a problem, Pete. Does the following work for you?

A web form with a div like:

<div class="myDiv">
....
</div>

and the web form sets Theme="SomeTheme" in the @ Page directive. Inside of the SomeTheme directory is a .css file with the following:

.myDiv
{
background-image: url('example.jpg');
}

The .jpg file is also inside the themes directory.

This does work for me as the browser will request the .jpg file relative to where it fetches the style sheet from, so even with web forms in different sub directories the path is valid.

Let me know if that works / makes sense. Getting a little fuzzy here late at night.

Thursday, August 03, 2006 8:48 AM by Merritt

# re: The MasterPage Article I Thought I’d Never Finish

Best article I've come across concerning Master pages. The section entitled "Headers, Scripts, and Meta Tags, Too" was extremely helpful to me.
Friday, August 04, 2006 1:27 AM by James Hebben

# re: The MasterPage Article I Thought I’d Never Finish

Fantastic article. It has helped me understand how master pages really work.

I have blogged a tidy solution to including javascript files in a consistent manner.

http://extraview.co.uk/blog/PermaLink,guid,a4bd0a9a-6bdc-4552-a946-3a82af0afc89.aspx
Tuesday, August 08, 2006 1:13 AM by Arne Bolstad

# re: The MasterPage Article I Thought I’d Never Finish

Hi,

thanks for a great article! When implementing the HttpModule i found that my login page crashed. This page is a stand alone page and does not belong to any MasterPage. I resolved it by doing a null check:

Page page = sender as Page;
if ((page != null) && (page.Master != null))
{
...
}

Just thought I should share this...

/Arne (Sweden)
Monday, August 14, 2006 3:02 PM by Antoine

# re: The MasterPage Article I Thought I’d Never Finish

Great article,

Thanks, it helped.

One note: in Javascript opened windows, the way to address controls on the opener also changes; I didn't figured it out yet though.
Friday, August 18, 2006 1:46 AM by James Newton-King

# Testing if a ContentPlaceHolder is Empty

K. Scott Allen , one of the many Scotts who seem to develop in .NET, has written a comprehensive article
Tuesday, August 22, 2006 1:03 AM by Ricky

# re: The MasterPage Article I Thought I’d Never Finish

Hi Scott,

Great article!

I have some problems though with my master page.
The master page has a backgroung image and a login.aspx as the startup content page. When i ran the project, the image is not displayed in the startup page (login.aspx) but when login is successful and control is transferred to my default.aspx the image is displayed.
In my web.config the authentication mode="forms". Whenever i change this to "windows" the project works fine. How can i display images in the master page when the "authentication=forms" in web.config ?

Hope you can help me.

Thanks.


Tuesday, August 22, 2006 6:32 AM by Scott Hungarter

# re: The MasterPage Article I Thought I’d Never Finish

I was searching for a very specific problem when i came across this article... specifically trying to use FindControl() within a MasterPage'd site. Awesome article! I found my answer and got a whole lot more too.
Thanks a million!
Wednesday, August 23, 2006 7:49 AM by scott

# re: The MasterPage Article I Thought I’d Never Finish

@Scott: Thank you for the compliment.

@Ricky: Check this post by ScottGu: http://weblogs.asp.net/scottgu/archive/2006/01/31/437027.aspx
Thursday, August 24, 2006 4:30 PM by Michael Shapiro

# Content-to-Content interactions

Scott,

Great article! The best one on this topic.

I have a question that was not covered in it though. In one of the content pages I have the following (simplified) setup - runat="server" omitted, etc.:

<asp:Content ContentPlaceHolderID="driver">
<asp:TextBox ID="tb">
</asp:Content>

<asp:Content ContentPlaceHolderID="data">
<asp:GridView DataSourceID="ds" />
<asp:ObjectDataSource ...>
<SelectParameters>
<asp:ControlParameter ControlID='<%= GetControlID("data", "tb") %>' .../>
</SelectParameters>
</asp:ObjectDataSource>
</asp:Content>

The problem is that GetControlID method is never called in this scenario and request is failing. Obviously, the ControlID parameter for the ControlParameter control is set before...

I've been banging on this problem for quite some time and couldn't find a solution. Any help would be greatly appreciated. It would be also very interesting to hear your recommendations regarding inter-contentPlaceholder controls interactions.

Thanks again for the superb article!
Michael
Saturday, August 26, 2006 1:11 PM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Michael: I don't believe you can use expressions that way. What I'd do is set the property programatically in PageLoad (ControlID = tb.ID).
Monday, August 28, 2006 6:56 AM by frank

# re: The MasterPage Article I Thought I’d Never Finish

Hi,

I am using a custom control dervied from compositecontrol class. I have a button in this control which fires an event. When I use this custom control in a normal aspx page it works fine, but in master page the event is not getting fired. Could you help?
Monday, August 28, 2006 9:28 AM by Mario

# re: The MasterPage Article I Thought I’d Never Finish

I'm trying to use the A Page Directive Approach but I get this error after creating the BasePage class and trying to make one of my pages inherit from it.

Error 1 Error parsing attribute 'metakeywords': Type 'System.Web.UI.Page' does not have a public property named 'metakeywords'. c:\inetpub\wwwroot\showMachines2.aspx 1

What can I do to fix this ??

Thanks,
Mario
Monday, August 28, 2006 2:42 PM by Roland

# re: The MasterPage Article I Thought I’d Never Finish

Thanks for the hard work you put into the article.

We put all this time into figuring out how to use something that is supposed to save us time. You have to ask yourself: was it worth it? Perhaps another excellent article called "Master Pages: Use them? or Avoid them?", would be in order to address the type of site it is worth using them on.
Sunday, September 03, 2006 10:53 PM by Ricardo

# Some other issue..

Scott, amazing article :) How the flow will works with few ContentPlaceHolders at the some MasterPage ?
Friday, September 08, 2006 8:53 AM by ED

# re: The MasterPage Article I Thought I’d Never Finish

Great suggestions on sharing the master page. However, how do I get the virtual directory to be visible as I'm developing in my IDE?
Thanks!
ED
Thursday, September 14, 2006 5:31 AM by Dalia

# re: The MasterPage Article I Thought I’d Never Finish

This is a great article, thanks.
Thursday, September 14, 2006 10:46 AM by Dot Net New Bee

# re: The MasterPage Article I Thought I’d Never Finish

Great information on Master/Content pages. Thanks.
I am trying to use the "Define a custom SendEmail event, and let each page subscribe to the event" but having problems to get it to work.

Is it possible to display the entire sample here for downloads?

I have the following code in my Content's page but keep getting this error message "No overload for 'EmailReport' matches delegate 'System.EventHandler'" . Can you please tell me what I am doing wrong? Thanks a lot!
---------------------------------------------
protected void Page_Init(object sender, System.EventArgs e)
{
Master.SendEmail += new System.EventHandler(this.EmailReport);
}

protected void EmailReport(object sender, classLibrary.SendEmailEventArgs e)
{
string address = e.ToAddress;
// do work
}
Saturday, September 16, 2006 10:11 PM by Patrick

# Page Directive Approach

Scott,

Meta tags is the only trouble we've had with Master pages. Anyway, I tried to implement as you've outlined in the article, to no avail. Here are my steps:

1) Create a new Class file in App_Code that inherits from Page (I've called this BasePage)
2) That class contains your code and seems to compile OK
3) I then changed the Default.aspx codebehind page to inherit from that new BasePage instead of the usual Page; this seems to match what you have as well since it's in the @Page directive.

Anyway, once I add in the "MetaKeywords" in the Page directive, it barfs that it's not an attribute of System.Web.UI.Page, even though I'm inheriting from my BasePage instead. I did not touch the Master file, as your example also did not seem to touch the Master file.

I tried the CodeFileBaseClass attribute as well but that gave me even more errors.

Any guidance is appreciated. :-)
Sunday, September 24, 2006 3:11 PM by Bill

# re: The MasterPage Article I Thought I’d Never Finish

This was a great article, but I am really bothered by something and was hoping you could clear this up for me. Basically, if you are using master pages, it would appear you cannot even use the basic Autopostback capabilities of, say, the dropdown listbox in a content page and show the selected element with an HTTP Request. Is this true?

I've been testing and it would appear so. This means that currently written applications that you plan on 'wiring up' to a Master Page can no longer use server-based forms that get even simple postbacks (i.e. Request["dropdownlist1"];).

In my testing, I did something this simple and it works without master pages, but once connected (and setting the MasterType virtual path), the code no longer retrieves the data.

Thoughts?
Tuesday, September 26, 2006 10:09 AM by Heather

# re: The MasterPage Article I Thought I’d Never Finish

I have a situation where I have created a master page and then a content page and then on that page I have put a webtab control and then on each individual tab I have put one web user control.

So now I would like to push a button on the web user control that is on the first tab and have the second tab appear or become active.

I need a way to access the webtab control from the web user control that is on the first tab.

This may not be a master page problem at all and if not, I appologize. Thank you.
Friday, October 06, 2006 4:28 AM by Richard Wilde

# re: The MasterPage Article I Thought I’d Never Finish

Hi.
Great article on master pages. We use masterpages in .net 2.0 and also use dreamweaver templates. This is so our customers use macromedia contribute to edit pages. This works great however the customer has the ability to change the title tag within contribute. we have a content control within ht e head to set the title tag. However asp.net always adds an empty title tag on the page as well so we end up with 2 title tags.

Is it possible to turn off the title in the page directive or remove it when the page is rendered?

Thanks
Saturday, October 07, 2006 12:17 PM by scott

# re: The MasterPage Article I Thought I’d Never Finish

@ Richard: I don't think there is a way to turn of Title in the @ Page directive after the page starts executing. It would have to be something that happens before the page compiles.

@ Heather: That is not really a master page problem, but I'd look at having the control raise an event to the page, and the page will then change the visibility on the tabs.

@ Bill: You have to be careful with using syntax like Request.Form["xyz"], because names can change. It would be better to access the drop down list through the field.

@ Patrick: I'd need to see some code. I believe you sent me an example in email :)
Thursday, October 19, 2006 10:28 AM by Ram

# re: The MasterPage Article I Thought I’d Never Finish

Scott,

Very informative article and thanks for that.

I have a question on Sharing the master page with multiple applications.

As you explained in your article, we are implementing with IIS sharing approach. With that approach, I am getting two types of errors

1.When we use MasterType in the aspx page, it added public get property in the corresponding designer file which is by design. But it did not recognize the masterpage type and so the build is failing. Of course the reason was, the application dll can not find the masterpage type. One way to solve this copy the master page project dll into this application bin directory. But whenever we make changes to Masterpages, we need to copy the dll back to application bin direcotry which is big maintenance issue in our case. Did you go through this?

2.Application content page could not find the masterpagefile and so source mode of the page is complaining as "masterpage file not found" Do you think it is VS 2005 issue?


Ram
Thursday, October 19, 2006 12:28 PM by scott

# re: The MasterPage Article I Thought I’d Never Finish

Ram:

In some cases I skip the strongly typed MasterPage property. Instead, I define an interface in a class library and reference the class lib from both the master page project and the web site project.

The master page can inherit from the interface and implement its members. The content pages cast the MasterPage property to this interface type and invoke the properties.
Friday, October 20, 2006 2:02 PM by Danielle

# re: The MasterPage Article I Thought I’d Never Finish

Thanks for such a wonderful article. I've been referring to it for awhile to help me programmatically set and reference members of three different master pages I use. The three master pages have quite a bit of overlap, and I decided today I could sandwich those three between a static top and base master so that I could have my base master page always doing the work to figure out the correct master page rather than writing that logic over and over in each .aspx page. SOOO, I have the "Content controls are allowed only in content page that references a master page" problem on my base master that programmatically sets one of three I immediately came here, and sure enough you had a fix...except the MasterPageFile="" trick doesn't seem to work in the @Master directive. Do you have any more tricks up your sleeve?
Wednesday, October 25, 2006 4:44 AM by Tom Clancy

# re: The MasterPage Article I Thought I’d Never Finish

Why would meta tags in a <head> with runat=server escape the contents inside of them? I have a block in a master page that looks like this:

<head runat="server">
...
<meta name="author" content="<%= MASTER_COMPANY_NAME %>" />
<meta name="copyright" content="<%= MASTER_COMPANY_NAME %> - <%= CurrentYear %>" />
...
</head>

When a page renders, they look like

<meta name="author" content="&lt;%= MASTER_COMPANY_NAME %>" />
<meta name="copyright" content="&lt;%= MASTER_COMPANY_NAME %> - &lt;%= CurrentYear %>" />
Friday, October 27, 2006 9:03 AM by sree

# re: The MasterPage Article I Thought I’d Never Finish

Scott,

After i read your article i created a master page implemengting the following interface:

public interface IMasterForm
{
string MasterFieldText
{
get;
}
}

after implementing the above interface in masterpage:

-------------------
public partial class MyMaster : System.Web.UI.MasterPage, IMasterForm
{
protected void Page_Load(object sender, EventArgs e)
{
if (ContentPlaceHolder1.TemplateControl.Page.PreviousPage != null)
{
IMasterForm form = ContentPlaceHolder1.TemplateControl.Page.PreviousPage.Master as IMasterForm;
if (form != null)
{
if (!string.IsNullOrEmpty(form.MasterFieldText))
{
//here i will set the label which is supposed to be in all the pages
setLabel = form.MasterFieldText;
}
}
}
}

public string setLabel
{
set
{
lblResult.Text = value;
}
get
{
return lblResult.Text;
}
}

#region IMasterForm Members

public string MasterFieldText
{
get { return setLabel; }
}

#endregion
}

------------------------------

I want to set the master page values only once in page1 and maintain the same master page values for the remaining pages(page2,page3,page4...)


page1.aspx.cs:


public partial class Page1: System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}

protected void Button1_Click(object sender, EventArgs e)
{
((MyMaster)Page.Master).setLabel = txtBox.Text;
}
}


page1.aspx:

<%@ Page Language="C#" MasterPageFile="~/MyMaster.master" AutoEventWireup="true" CodeFile="Page1.aspx.cs" Inherits="Page1" Title="Untitled Page" %>
<asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
<asp:Label runat=server ID=myLableResult Text="TestTransfer1 Page"></asp:Label>
<asp:Button ID="Button1" runat="server" Text="Button" PostBackUrl="~/Page2.aspx" />
</asp:Content>

---------------

After i implemented this logic i could able to browse through into different pages with postbackurl setting in each page control to a different page.

Is this a good idea or is there any other way to implement? as i don't want to implement the interface in each child web form and carry the values along with the child web pages.
</