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

Print | posted @ Wednesday, April 12, 2006 5:09 AM

Comments on this entry:

Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Peter Kellner at 4/12/2006 4:25 PM

Great Article! I never realized there was so many things to worry about on a Master Page
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Jun Meng at 4/12/2006 5:51 PM

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?
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 4/12/2006 6:27 PM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by steve at 4/14/2006 4:55 PM

Outstanding! Thanks.
  
Gravatar # 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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 4/18/2006 5:22 PM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Jon at 4/18/2006 9:16 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Chris at 4/18/2006 11:24 PM

> 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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 4/19/2006 3:17 AM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scottgu@microsoft.com at 4/19/2006 7:15 AM

Chris -- I posted a reply to your comment on my blog post: weblogs.asp.net/.../443276.aspx#FeedBack

Hope this helps,

Scott
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Ryan Anderson at 4/19/2006 4:18 PM

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! :)
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Jon at 4/19/2006 9:57 PM

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!!!
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Nisar Khan at 4/21/2006 1:59 AM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Nisar Khan at 4/21/2006 2:45 AM

do you have anything related with:

Content Page To Master Page Interaction?

thank you
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Scott Allen at 4/21/2006 2:00 PM

Yes, the article covers interaction in both directions.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Scott Allen at 4/21/2006 2:03 PM

Nisar:

The event will be null until someone subscribes to the event. Typically the page would subscribe to the event (SendEmail += new SendEmailEventHandler(...))
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Brian at 4/21/2006 8:03 PM

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;
}
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by steve at 4/23/2006 7:26 PM

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!
  
Gravatar # EXCELLENT Article
by Atul Reddy at 4/25/2006 12:59 PM

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
  
Gravatar # re: Question on adding controls to master pages
by Vani at 4/25/2006 8:53 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Ed at 4/25/2006 11:46 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 4/27/2006 2:17 AM

Ed: You shouldn't have to "new BaseMaster()" if that is the base class for your master page. It's an inheritance relationship.
  
Gravatar # UserControls inside the ContentPlaceHolders sitting on Master Pages/Content Pages
by Diego Beltran at 4/28/2006 4:07 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by trevork at 4/28/2006 6:13 PM

A well constructed, useful article - thanks!

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

Trevor
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Tyler Carver at 5/2/2006 5:43 AM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by James Spibey at 5/2/2006 8:29 AM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by TristanK at 5/2/2006 1:12 PM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Scott at 5/2/2006 1:22 PM

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).
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 5/2/2006 1:24 PM

Thanks, Tristan.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by James Spibey at 5/2/2006 3:28 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Dan O at 5/2/2006 11:10 PM

Great article - one of the best asp.net articles I have seen.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Tyler Carver at 5/3/2006 4:29 AM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Kevin at 5/4/2006 2:36 AM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Priya at 5/4/2006 6:50 PM

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.

  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by matt vaughn at 5/4/2006 9:44 PM

"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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 5/5/2006 2:38 AM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Priya Raj at 5/5/2006 7:19 PM

Scott, I emailed you the code details.

Thanks,
Priya
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Vik at 5/8/2006 5:07 PM

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

  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Avi at 5/16/2006 10:41 PM

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?
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by J.P. at 5/18/2006 5:38 AM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 5/18/2006 2:31 PM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by J.P. at 5/19/2006 4:43 PM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Munir Syed at 5/24/2006 1:09 AM

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!
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Steve at 6/2/2006 5:31 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 6/2/2006 8:54 PM

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 :)
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Gene at 6/3/2006 9:57 PM

Thank you for your work on this article; it helped me a great deal.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Adam Tibi at 6/5/2006 5:05 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Peter Bromberg at 6/6/2006 9:12 PM

Scott,
Best "Get under the hood" Master-Mechanic article on MasterPages on the net. Good work.
Appreciate it!
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Rich at 6/12/2006 1:45 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by dokmanc at 6/13/2006 4:06 AM

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:

groups.google.com/.../eb862a9635f5ad3e
  
Gravatar # re: Broken Urls
by Andy Lee at 6/16/2006 8:25 AM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by John Gillespie at 6/18/2006 1:35 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Fabiano Arruda at 6/28/2006 4:12 AM

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

thank you very much

Fabiano Arruda
fabiano.arruda@cesar.org.br
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Sukki at 6/28/2006 5:55 AM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Markus at 6/29/2006 6:44 AM

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!
  
Gravatar # Page Directive Approach
by Eric at 6/29/2006 1:42 PM

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. :-)
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 6/29/2006 3:10 PM

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,
  
Gravatar # re: Page Directive Continued
by Eric at 6/30/2006 7:02 PM

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! :-)
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 7/3/2006 12:16 AM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by doWhileSomething at 7/6/2006 12:35 AM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 7/6/2006 1:03 PM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by sbyard at 7/10/2006 3:43 PM

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>");
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by JetBrain at 7/17/2006 12:43 PM

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
  
Gravatar # Excellent!
by Zaheer Ahmad at 7/24/2006 11:31 AM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by arun at 7/28/2006 9:27 PM

i like this artical because it explain how to fine the controls in the master pages and other important features of the mastser pages
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Peter Kellner at 7/29/2006 4:26 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 7/30/2006 5:33 PM

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: www.codinghorror.com/blog/archives/000319.html
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Peter Kellner at 7/30/2006 9:59 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 7/31/2006 2:58 AM

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.

  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Merritt at 8/3/2006 3:48 PM

Best article I've come across concerning Master pages. The section entitled "Headers, Scripts, and Meta Tags, Too" was extremely helpful to me.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by James Hebben at 8/4/2006 8:27 AM

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.

extraview.co.uk/...
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Arne Bolstad at 8/8/2006 8:13 AM

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)
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Antoine at 8/14/2006 10:02 PM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Ricky at 8/22/2006 8:03 AM

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.


  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Scott Hungarter at 8/22/2006 1:32 PM

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!
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 8/23/2006 2:49 PM

@Scott: Thank you for the compliment.

@Ricky: Check this post by ScottGu: weblogs.asp.net/.../437027.aspx
  
Gravatar # Content-to-Content interactions
by Michael Shapiro at 8/24/2006 11:30 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 8/26/2006 8:11 PM

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).
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by frank at 8/28/2006 1:56 PM

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?
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Mario at 8/28/2006 4:28 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Roland at 8/28/2006 9:42 PM

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.
  
Gravatar # Some other issue..
by Ricardo at 9/4/2006 5:53 AM

Scott, amazing article :) How the flow will works with few ContentPlaceHolders at the some MasterPage ?
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by ED at 9/8/2006 3:53 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Dalia at 9/14/2006 12:31 PM

This is a great article, thanks.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Dot Net New Bee at 9/14/2006 5:46 PM

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
}
  
Gravatar # Page Directive Approach
by Patrick at 9/17/2006 5:11 AM

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. :-)
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Bill at 9/24/2006 10:11 PM

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?
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Heather at 9/26/2006 5:09 PM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Richard Wilde at 10/6/2006 11:28 AM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 10/7/2006 7:17 PM

@ 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 :)
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Ram at 10/19/2006 5:28 PM

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
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 10/19/2006 7:28 PM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Danielle at 10/20/2006 9:02 PM

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?
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Tom Clancy at 10/25/2006 11:44 AM

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 %>" />
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by sree at 10/27/2006 4:03 PM

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.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by scott at 10/29/2006 8:34 PM

@ Danielle:

Not sure I follow the question. ScottGu expanded on the nested master tricks here: weblogs.asp.net/.../430382.aspx.

@ Tom: I would probably add those tags using code behind.

@ Sree: I would probably let the master page maintain its state in the database, or in Session. This keeps the content page and master page a bit more seperated.



  
Gravatar # Form in a form
by Amritha at 11/3/2006 5:49 PM

Hi,

I am developing an application using ASP.NET.

I have a form and would like to include a form within it.

Any help will be appreciated.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by David Austin at 11/7/2006 12:24 PM

Thanks for the article. Amazing!
I find myself very frustrated by the difficulties in using javascript libraries with master pages. I don't really understand the methods posted above for javascript inclusion, so I tried one of the methods you suggested, with no success I'm afraid.
I have a questions.aspx page and a questions.js library in the root directory of my web app. The master page is in a master directory ie:
~/master/template1.master.
I can't get VS 2005 to debug javascript written into the aspx page so I have been using included js files for the debugging as well as the efficiency of grouping functionality.

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

I think this should work, but it doesn't....

Dim si As HtmlGenericControl = New HtmlGenericControl()
si.TagName = "script"
si.Attributes("runat") = "server"
si.Attributes.Add("type", "text/javascript")
si.Attributes.Add("src", "~/Questions.js")
Master.Page.Header.Controls.Add(si)

Any ideas or suggestions would be great.
thanks for your time
David
  
Gravatar # re: The MasterPage cannot access Session?
by Mystifier0505 at 11/7/2006 12:41 PM

Hi!

Master Pages cannot access Session?

Myth.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Saravana Kumar at 12/4/2006 5:44 AM

I have page onherited from nested master page.
The base master page has 2 user control and i conent placeholder. my problem is the button click event is not getting fired in the page. It's not at all doing post back.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Graham at 12/4/2006 9:48 AM

Scott,
I'm just starting to use master pages and have put all my navigation buttons there. I'm trying to reset them using the following code structure but can't find any buttons. I tried getting hold of the contentplaceholder, but can't loop through it.
protected void Reset_Buttons()
{
foreach(Control ctrl in Page.Master.Controls)
{
if(ctrl is Button)
{
Button btn = (Button)ctrl;
MessageBox.Show(btn.Text);
}
}
}

thanks,
Graham
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Scott Allen at 12/4/2006 4:22 PM

@David: The "~" character won't work in your example. You'll need to explicitly wrap the URL in a call to Page.ResolveClientUrl to have ASP.NET evaluate the correct path to your .js file.

@Saravana: That is a scenario that should work find. I can't say more without seeing the code.

@Graham: MessageBox won't work on the server. It pops up a windows message box that nobody would be able to see.

Also, the buttons are probably inside a form control. Set trace="true" in your @ Page directive and see what the button's parent control is. Loop through the parent control's Controls collection. Hope that makes sense.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Keren at 12/12/2006 4:05 PM

Hi scott
great article, I find it very useful, 10X.
I have request can someone please translate the following VB code to C#

<%@ Master Language="VB" %>

<script runat="server">

Public Event SendEmail As SendEmailEventHandler

Protected Sub SendEmailButton_Click(ByVal sender As Object, _
ByVal e As System.EventArgs)

Dim eventArgs As New SendEmailEventArgs(EmailAddressBox.Text)
RaiseEvent SendEmail(Me, eventArgs)

End Sub

</script>

<script runat="server">

Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs)
AddHandler Master.SendEmail, AddressOf EmailReport
End Sub

Protected Sub EmailReport(ByVal sender As Object, ByVal e As SendEmailEventArgs)

Dim address As String = e.ToAddress

' do work

End Sub

</script>

I cannot understand what are the orders:
RaiseEvent SendEmail(Me, eventArgs)
and
AddHandler Master.SendEmail, AddressOf EmailReport
what are the parallel functions in C# that I have to wirte down?

and again 10X
Keren
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Akhilesh at 1/11/2007 10:32 AM

Hi,
Thank you very much for such a nice article. I wish I should have read it before submitting my project. But any how I have got a great help I was stuck for running a javascript function and I finally found that I should use ctl00_ContentPlaceHolder1_Label1 in place of label1 in content page. Can you please tell what should be used for master Page Controls?????
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Saud at 1/12/2007 11:26 AM

That was the best article i ever read on Master pages. I am using your tips to write an article which covers Master Pages and Factory Pattern. That was mind Blowing.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Bohemian at 1/12/2007 5:30 PM

I have searched high and low and you are the only one whom even comes close to this topic and I am wondering if you can shed some light on it…
“Dynamic Server Controls, Events in content pages that also utilize a MasterPage…”
Basically, for this test I have some dynamic server controls, a dropdown, button and textbox for example…
They are all created in the page_init of the content page as are the event handlers…
Pretty standard stuff, when there is no MasterPage the events are raised as anticipated, when a plain jane MasterPage is added, the dynamic events for said dynamic server controls are not raised…
Can’t seem to make it fly…
Can you shed any light on the subject, possibly a blog article with a functional sample?
Thanks in advance.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Adam at 1/17/2007 5:07 PM

Thanks for a great Article!
I was wondering if someone would help me with an issue that's driving me insane.

I have a menu control that works fine on an aspx page. However, when I move the control to a Master page, it behaves differently.

Specifically, the when you hover over a link in the Menu control, the entire <td> background should change color. When the control is on the Master page, only the background around the actual text changes.

As far as I can tell, the only difference in the resulting HTML is in the class attribute.

e.g,
class="Header1_Menu1_1 TopNavLink Header1_Menu1_3" (when it's on the page)

class="ctl00_Header1_Menu1_1 TopNavLink ctl00_Header1_Menu1_3" (when it's on the Master page)

Anyone know why? My designer won't let this slide by!
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Michael Holm Andersen at 1/18/2007 1:35 PM

Hi Scott

Great article!

I’m developing a CMS like application, where I would like to use a MasterPage for the “outer design” and a single Content page, which dynamic builds the “inner content” for the page, loading UserControls and “injecting” these into the Content Page.

What I have is this:

.aspx file

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="mhaDynContent.aspx.cs" Inherits="mhaDynContent" Title="Untitled Page" %>


.aspx.cs file

protected void Page_PreInit(object sender, EventArgs e)
{
this.AppRelativeVirtualPath = "~/mhaDefault.aspx";
this.MasterPageFile = "~/MasterPage.master";
base.AddContentTemplate("ContentPlaceHolder1", new TestContent());
}

public class TestContent : System.Web.UI.ITemplate

{
void System.Web.UI.ITemplate.InstantiateIn(Control container)

{
container.Controls.Add(new LiteralControl("Hello World"));
//Control toAdd = LoadControl("mhaCalendar.ascx");
//container.Controls.Add(toAdd);
//UserControl a = new UserControl();
//a.LoadControl("mhaCalendar.ascx");
//container.Controls.Add(a);
}
}

I can easily add a new control (like e.g. the LiteralControl to the “container”, but what I really would like to do is load (“inject”) a UserControl into the container and I can’t make this work (I’ve commented out some of my code – attempts :)

I hope you understand my problem and any help would be appreciated.

Best regards,

Michael Holm Andersen
  
Gravatar # Master Page Inheritance With Code-Beside Model
by Kevin at 1/21/2007 7:36 PM

I am having problems getting the master page inheritance to work with the code-beside model. When I follow the example, I can get the visual inheritance to work, but it forces me to put any code "inline" in the master page rather than in a code-beside file.

Does anyone know how I would take this example below and change it to inherit from the base master page class defined below?
-----------------------------------------------------------------------
File: default.master
-----------------------------------------------------------------------
<%@ Master Language="C#" AutoEventWireup="true" CodeFile="default.master.cs" Inherits="Resources_default" %>
...
-----------------------------------------------------------------------
File: default.master.cs
-----------------------------------------------------------------------
using System.Collections;
...
public partial class Resources_default : System.Web.UI.MasterPage
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
Trace.Warn("MADE IT");
}
}
}
-----------------------------------------------------------------------
File: BaseMasterPage.cs (located in App_Code)
-----------------------------------------------------------------------
using System;
...
public abstract class BaseMasterPage : MasterPage
{
//NOTHING HERE YET
}
-----------------------------------------------------------------------
I cannot figure out how to "wire" it up so that my events in the default.master.cs are handled.

I appreciate any suggestions.

Kevin
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Bilge at 1/22/2007 12:17 AM

This is an awesome article. I do not have time to read all of it now, but what I did read was invaluable research and insight. I have bookmarked it for later reference. Thanks.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by TraceyM at 1/22/2007 4:26 PM

Good information, thanks. Anyway to take this a step deeper? I trying to programmatically set the Navigation.Url property of a hyperlink web control inside a ItemTemplate in the form view web control that sits on a content page that has a master page. I'm trying to set this in detail.aspx.vb, I haven't had much luck.

Any assistance would be great...

Master Page: MasterPage.master
Content Page: detail.aspx
Form View Control: FVDetail
HyperLink Control: mapLink
  
Gravatar # Help needed
by Shoaib at 1/23/2007 5:49 AM

I have a menu on my master page. When the sub menu opens, it is displayed behind the content in the content placeholder at the center of the page.

I have tried many ways but couldnt solve the problem. I will be thankful if somebody can solve my problem
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by AustinDeveloper at 1/25/2007 4:16 AM

I just wanted to leave a quick note to say "thanks" for writing this article. I was looking for a good way to allow content pages to override (or augment) the stylesheets included in the master page. This article answered that question (and several I hadn't yet thought of) extremely well. Great work!
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Kirill at 10/9/2009 1:42 AM

Thanks! Best article about master pages I've ever seen.
  
Gravatar # And if i want load a Dynamic Menu in the Master Page
by Fidel at 10/17/2009 8:40 AM

Look interesting, but, what i want load a Dynamic Menu based in the User Profile, and the data is in a database, how i make a reference in the "MainMenu" ID control? in the page.aspx.vb y recive a message MainMenu not defined. Can you help me with the solution to reference a Object in the CodeBehind? Thank you for your support.
  
Gravatar # Asp.net upload and download code
by arsema at 10/20/2009 8:06 AM

Hello every one please help me I am beginner to develop asp.net please help me if you are interested. I try to develop my own sight asp.net with C# ,please help me the upload code and download code asp.net with C# code
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Mukesh at 10/26/2009 11:46 AM

Thanks for the article. It's very useful.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Bhavana at 11/20/2009 10:39 PM

Great article. Thanks Scott!
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Sri at 11/24/2009 2:16 PM

You saved my day! There is stuff in here I did not find elsewhere (topic: "Break URLS..."). Thank you so much!
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by atul at 1/1/2010 1:07 AM

Thanks buddy it was great help.
I was wondering to call an event from master page. your article helped me out.
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Navjot Singh at 1/6/2010 12:18 AM

"Realy You Give A Good And Very Important Information about master Pages .. Thanks..."
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Satish Kacham at 2/2/2010 12:00 AM

Thanks Scott,
You are doing great job.

Cheers,
Satish Kacham
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Dinil at 2/24/2010 3:31 AM

Great work man....
  
Gravatar # re: The MasterPage Article I Thought I’d Never Finish
by Luis Fernando Forero at 3/11/2010 9:48 AM

Great article I have a question
I want to change a label in my master page. Thanks to your article I have manage to do that.
The problem is that I have to do that in every page, is there a way to optimize that?
Thanks
  
Gravatar # accessing a label on a Header control
by Sheila at 3/16/2010 5:31 PM

Thanks for the article!

I am still having a little trouble. I built a Master page, build a separate Header control, added the control to the master page.

Now on other pages, I would like to access and change the label on the Header control.

Is there a way to do this?

-smc
  

Your comment:

Title:
Name:
Email:
Website:
 
Italic Underline Blockquote Hyperlink
 
 
Please add 2 and 3 and type the answer here: