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.

C#
blog comments powered by Disqus

Get In Touch

Follow me online at TwitterFacebook or Flickr.

Latest Tweets