How to fire the client side onload event in asp.net page inheriting masterpage.

In this asp.net tutorial you will learn how to fire the client side onload event in asp.net page inheriting masterpage. In simple asp.net page you can fire the client side onload event in <body> tag like this <body onload="yourjavascriptfunction();"> but in asp.net pages inheriting masterpage we don’t have any <body> tag as this <body> tag is available in masterpage and if we fire the javascript onload event their at masterpage then its mean it will be fired on all those web pages inheriting that masterpage. So let's have a look over how to do so. There are two methods and both are very simple


Method 1

<script language="javascript" type="text/javascript">
window.onload = function(){ alert("Hello"); }
</script>


Method 2

protected void Page_Load(object sender, EventArgs e)
{
HtmlGenericControl body = this.Master.FindControl("body") as HtmlGenericControl;
body.Attributes.Add("onLoad", "alert('Hello')");
}
If you want second method to work then you must have to give id to the <body> tag in masterpage like this <body id="body">

So these are the ways to fire the client side onload event in asp.net page inheriting master page.

0 comments: