Click here to Skip to main content
Email Password   helpLost your password?

Problem

If you are using Master Pages in an ASP.NET application and you need to add an attribute to the <BODY> tag from a Content Page -- for instance, to set a client script function for the onload event of the page -- you will find that you can't do it directly because the <BODY> tag is in the Master Page, not in your Content Page.

Solution

Make the <BODY> tag on the Master Page a public property, so you can access it from any Content Page. First, promote the <BODY> tag in the Master Page to an ASP.NET server control. Change:

<BODY>

to:

<BODY id="MasterPageBodyTag" runat="server">

Now that the body tag is a server control, you can configure access to it as a public property in the Master Page code behind file:

using System.Web.UI.HtmlControls;
public partial class MyMasterPage : System.Web.UI.MasterPage
{
    public HtmlGenericControl BodyTag
    {
        get
        {
            return MasterPageBodyTag;
        }
        set
        {
            MasterPageBodyTag = value;
        }
    }
...

Note that the MasterPageBodyTag server control is of type System.Web.UI.HtmlControls.HtmlGenericControl. To demonstrate this, just set a breakpoint in the Page_Load function in the code behind file, run the ASP.NET project in debug mode to that point, and execute ?MasterPageBodyTag.GetType().ToString() in the Immediate Window. To use this property from a Content Page, first declare the type of your Master Page in your Content Page's ASPX file:

<%@ MasterType TypeName="MyMasterPage" %>

Then somewhere in your Content Page's code behind file, use the Master Page's BodyTag property to add an attribute to the <BODY> tag:

protected void Page_Load(object sender, EventArgs e)
{
    Master.BodyTag.Attributes.Add("onload", "SayHello()");
...

This example, of course, assumes that there is a SayHello() client script in this Content Page. Running the application to the Content Page and then viewing the source code in the browser will show that the onload="SayHello()" attribute was added to the <BODY> tag. This technique should work for any HTML tag in the Master Page that you wish to access from a Content Page.

History

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralMy simple solution to this
Rattlehunter
9:29 10 Nov '09  
I am not a programmer and I bet this solution is BAD but it works . ..

I put the <body> tag INSIDE a content place holder on the master page.  

For most content pages I don't want to change it but on my map page I need a couple of google map related things so on those pages I over ride the default content with my revised body tag

<body onload="initialize()" onunload="GUnload()>

So it looks like

Master page

<asp:contentplaceholder ID="bodytag" runat="server">
<body>
</asp:contentplaceholder>


Most pages don't call that place holder - the default gets used

On the map master page

<asp:Content ID="Content0" ContentPlaceHolderID="BodyTag" Runat="Server">
<body onload="initialize()" onunload="GUnload()">
</asp:Content>

It works but if it is really bad practice please remove this post.

Good luck!
Generalperfect
ev cabrera
7:35 5 Jun '08  
exactly what i was looking for. needed javascript to disable back navigation in onunload event, but only for certain conditions within a content page.
thanks.
GeneralHelp...
AD34
11:41 28 Apr '08  
Does anyone have samples of doing this with VB?

I can't get this to work, I have to be close but just missing something, if anyone has a sample using VB with Code Behind file, I would sure appreciate it if you would be willing to share it.

Thanks
AD34
GeneralI dont get this...
Member 3851879
21:34 25 Mar '08  
I am new to asp.net, so this might be a silly question Smile

Most tutorials i have followed, has a masterpage. The contentplaceholder is a holder for the aspx pages and usercontrols
are where you can have MenuSystem, and so on in a usercontrol and link it to the masterpage.

isent it better to make a <body> in a aspx page global rather than the master's body? If you have a create Textbox button control inside a user control, in the masterpage, you would rather create to a certain aspx page than the masterpage body - or am i wrong??? Smile </body>
GeneralA more simple way
justin.moses
10:38 21 Aug '07  
If you set your master page body tag to:
<body id="master_body" runat="server">
Then all you need to do is add this on any page that uses the master:
public void Page_Load(Object sender, EventArgs e)
{
//Inject onload and unload
HtmlGenericControl body = (HtmlGenericControl)Master.FindControl("master_body");
body.Attributes.Add("onload", "someFunction()");
body.Attributes.Add("onunload", "anotherFunction()");

}

I don't use code behind pages and this works great.
GeneralRe: A more simple way
psychrometrics
4:36 28 Sep '07  
I like this simple approach but can not get it to work. I think I am missing something simple.

In my Content page I have:

function void SayHello() {
alert("Hello");
}


and in the Content page code behind:

body.Attributes.Add("onload", "SayHello()");

everything else is the same as your post.
QuestionRe: A more simple way
justin.moses
5:11 28 Sep '07  
I use the method I mentioned a lot... I know it works.

Are you sure you have runat="server" in your body tag?
AnswerRe: A more simple way
psychrometrics
8:26 1 Oct '07  
You are absolutely right it works perfectly. I had another issue in my script that wa causing a problem. D'Oh!

Thanks!
GeneralRe: A more simple way
mln6937
23:38 15 Feb '08  
Hi,
A long time You wrote this, I know but I'm trying to convert Your code and use in VB. It would really be nice if You could help me.

Thanks
GeneralGood job
CoolBreeze812
17:01 7 Aug '07  
I have a similar write up I did on my blog. I essentially do the same thing to provide an alternative to using FindControl for accessing the properties of controls on MasterPages from other Content pages. This allows you to access for instance the text property of a TextBox control on the MasterPage from a Content page in a strongly type manner.

http://lspence.blogspot.com


lspence.blogspot.com

GeneralWhat about Master page body attributes ???
CWinKY
6:20 7 Aug '07  
I found this solution very interesting, cause I'm trying to solve the same issue. Trying to run a onload javascript function from the content page.

What about if also have a onload function in the Master Page?

<body id="MasterPageBodyTag" runat="server" önload="setInterval('refeshLogo()',10000);">
Currently I'm getting a error "Too many characters in character literal".

But it works if I remove the onLoad function from Master page.

Any thoughts?

I've also looked at Page.ClientScript.RegisterStartupScript which will works okay to add a onLoad function in content page, BUT I also need a onUnLoad event to that I need to attach code to ... but not sure how with ClientScript. It makes sense I should be able to use the code from this article to accomplish, but the error I'm getting isn't giving me much hope.

Thanks ....

Questionuser control access
Kamagurka
19:12 6 Aug '07  
Hi,
Great article!
I'm trying to read attribute values from within a user control. So I could easily configure the user control to behave in certain ways depending on it's tag attribute values. Currently I'm having difficulties accessing it's tag's attributes in the Master page. Can anyone point me in the right direction?
The Master page tag looks like this: <hnuc:UCIHeaderNav id="UsRTab" runat="server" /> and it renders custom html just fine, but I don't know how to access it's defining tag's attributes from within the control itself. What am I missing?
GeneralGreat, but question
Jamie Nordmeyer
6:25 30 Jul '07  
Great tip, but one question. Have you, or anybody else, ever been able to figure out how to modify the base element in the header? Currently, I'm just doing something like this:

// HTML head element must, of course, have runat="server" specified.
HtmlGenericControl baseElm = new HtmlGenericControl("base");
baseElm.Attributes["href"] = "Some/Sub/Folders/";
Page.Header.Controls.Add(baseElm);


Kyosa Jamie Nordmeyer - Taekwondo Yi (2nd) Dan
Portland, Oregon, USA
www.defaultn.com

QuestionHELP I had this problem few days ago and abandoned this solution....
KarmasAgent
21:19 17 Jul '07  
... because when I added attributes to my body tag it wiped out all other body tag attributes in my actual stylesheet.
The stylesheet is loaded in code-behind after a browser check (stewwwwpid IE6 makes "gymnastics" my second hobby) in the Page_Load method that also displays different header and logos if its IE6. When I attempt to alter the <body> properties in the same manner, by appending styles at runtime to those in the stylesheet it has no effect.

NOW, obviously I could do another browser check on the client side to control specific background attributes with JavaScript but I'd like to only do that once per page load frankly and not maintain two spots for browser sniffs..

Let me clarify, I didn't abandon YOUR solution, I came to this same solution on my own after a few hours and even more grey hairs, seeing YOUR solution gave me hope I actually was on the right track... I'm sorry if this is a stupid question, i'm a designer doing c# to make my designs work, worse than a n00b I tell ya.

Confused
Questionaccess from Control
OmidH
19:58 17 Jul '07  
You have any Idea how to access the BodyTag from a Control???

thanks in advance,
Omid
Generalgood!!
nikhilmittal
1:49 16 Jul '07  
hi
very nice thought
Generalgood job!
york zhang
0:29 15 Jul '07  
very nice ! in this way i can do more things i want!Smile thx!
GeneralGood thinking
Adam Tibi
6:32 6 Jul '07  
Hi

You can use this idea to access all HTML elements contained in the MasterPage, not just the body element.

You can access the meta tags and the html tag, for example.

Going a step further you can reuse this in all your projects and a good way to do that is to use the Page Controller design design.

Regards,
Adam Tibi

Make it simple, as simple as possible, but not simpler.

GeneralWhy would you want to do this?
Kevnz
18:53 1 Jul '07  
For the life of me I can't see this being a good idea. There are such better ways to attach javascript events to a page.
GeneralRe: Why would you want to do this?
Chuck Bevitt
14:03 2 Jul '07  
OK - I'm always willing to learn. What would be another way to do this?
GeneralRe: Why would you want to do this?
Davide Icardi
15:08 2 Jul '07  
Currently I'm not sure that this is the exact syntax but I think that you can register a client script with a code like this:
page.load = yourJsFunction;
... or a similar code.

But in my opinion your solution is a little better (more object oriented ...).

Davide
GeneralRe: Why would you want to do this?
shroomy
8:05 16 Oct '07  
Its much easier to maintain if you keep all the code in the codebehind.

I used this approach for adding an onresize handler for the few pages that needed it.
and also to change the scroll to be no.

I even know of a way to change the body to scroll ="no" besides this, though im sure there is a way.

thanks for the post

GeneralRe: Why would you want to do this?
KellyLeahy
15:37 2 Jul '07  
You're missing the point. The point of this is to show how to add attributes to the body tag, not how to add script to the page. Of course, adding script to the page is one possible use for this, but as you said, this may not be the best way to do that. It is, however, the best way to gain access to the entire "body" object in server-side code so that you can make attribute additions, style changes, etc. I've done this many times, in fact, both in master pages and in my regular pages as well. I also recommend the use of the @MasterType directive on your "child" pages, so that you can refer to the master page by a strongly typed reference.

Kelly
GeneralRe: Why would you want to do this?
Edelman
3:21 7 Aug '07  
basically, you can use the same masterpage and style it differently. <body id="homepage"> and <body id="downpage"> can be two completely different looking pages if you write your CSS correctly. this is a very useful idea.

DotNetDiscussion[^]
GeneralGreat
Ben Daniel
16:12 28 Jun '07  
I've wondered how to do this very thing before myself so this is great. Thanks. Smile

Thanks,
Ben Smile


Last Updated 30 Jul 2007 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2010