HowTo: Add a body onload script to a page that uses a MasterPage
By rickvdbosch
- 1 minutes read - 176 wordsWhen you use a MasterPage to define the design of your website, you might come across the problem that there is no body element in a web content form. This can be a problem when you want to add an onload script to a specific page. You could of course add the onload on the MasterPage, but you might not want the script to run on every page. There are several workarounds to fix this ‘problem’. The one I used last week was to do the following:
- Add the
runat=”server”
tag on the body in the MasterPage - Add a unique ID on the body in the MasterPage
- Add a method to the MasterPage to set the onload for the body. This might look a bit like this (of course you can also have the script for the load be a parameter for the method):
internal void SetBodyLoad()
{
MasterPageBody.Attributes.Add("onLoad", "initialize()");
}
- Add this line of code in the Page_Load of the page you want to have the onload:
((MasterPageName)Master).SetBodyLoad();
This worked for me! Hope this helps.