Master Page and Body Onload Event

Sometimes you need to fire an event using the body onload just like shown below:

<body onload="alert('Hello World')"> Some data </body>

Now, if you are using the Master Page and writing the above piece of code in the master page then it will be fired for every page that inherits from the master page. But, you really need this to be fired only for a specific page. Here is a simple solution for this problem.

In the master page make the body a control by giving the runat="server" attribute and a name.

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

Next, use the following code in the Page_Load event of the page (Default.aspx or any other page which inherits from the master page).

 HtmlGenericControl body = (HtmlGenericControl)
 Page.Master.FindControl("MyBody");
       body.Attributes.Add("onload", "alert('hello world')"); 

And, thats it! Now the body event is only generated for a particular page.

powered by IMHO 1.3

Print | posted @ Tuesday, April 25, 2006 10:37 PM

Twitter