Dynamically set the Body Onload attribute when using MasterPages

If you use MasterPages in your .Net website there will be a time when you want to load some javascript on a certain page and have it called OnLoad within the Body tag. A good example is when you use Google Maps.

When setting up your Google Map you will need to place javascript in the header of your page and you also need to set the Body OnLoad and UnLoad attributes. You could place the javascript in the MasterPage and be done with it but that is such a waste as usually you only want the Map to show on a contact page or similar. So how do you set the onBody attribute from within a child page?

In your MasterPage aspx file find the opening Body tag and give it an ID value and runat value eg:

<body runat="server" id="MainBody">

Now that we have given the MasterPage body tag an ID we can reference it within our child page and tell .net to update the Body tag with the attributes we want. You can do this by using the following piece of code. This code adds the Google Maps OnLoad and UnLoad javascript calls to the body tag.

 

HtmlGenericControl body = (HtmlGenericControl)
Page.Master.FindControl("MainBody");
body.Attributes.Add("onload", "load();");
body.Attributes.Add("onunload", "GUnload();");

 

The advantage of doing this is that we do not need to include the javascript on all the other pages that don't require it on our site.

Tags:

Comments

8/20/2009 10:51:26 AM #

Ron Rogers

Thanks for the great blog.  Would you explain how to simply set a unique body tag for each page using a master page and C#?  I am using a CSS based navigation menu and I need a unique body tag for it to work properly.  Kind Regards.  PS.  You reside near some great golf, I get there about every other year and love it.

Ron Rogers |

8/21/2009 1:46:52 AM #

richard reddy

Hi Ron,

If you want to set a CSS class in your Body tag on PageLoad that is different for each page you could try something like this:

In codebehind Page Load for each page (not masterpage) put in:
using System.Web.UI.HtmlControls;

protected void Page_Load(object sender, EventArgs e)
    {
        HtmlGenericControl body = (HtmlGenericControl)  
        Page.Master.FindControl("MainBody");  
        body.Attributes.Add("Class", "myClass");
    }

Just change the "myClass" value to be whatever CSS class you want in the Body tag for that particular page. Hope that helps!

As for the golf, I don't really play myself (I assume Tiger Woods on my PlayStation doesn't count!). A great course in Cork is the Old Head Golf Course in Kinsale though, stunning place to play - but it's kind of pricey! Check out oldhead.com for more.

richard reddy |

Comments are closed