Need to run a javascript in the masterpage body onload event? Most likely you would not want the script to run on every child page. Therefore, the real question is how to run a javascript in the content page onload event. Unfortunately, the asp:Content tag does not support the onload method. But here is how I got it to work.
Let’s suppose I have a hidden button in my form and I would like to execute the button’s click event using javascript in the body onload.
<asp:button id="MyHiddenButton" style="VISIBILITY: hidden" runat="server" CausesValidation="False" BorderStyle="None" EnableTheming="false" OnClick="MyHiddenButton_Click"></asp:button>
In a regular Page without master pages this is what my body tag would look like:
<body onload="javascript:document.forms['MyForm']['MyHiddenButton'].click();>
In a regular Page with master pages you can not use the load method so this is what you need to do:
1) At run time, do a “view source” in your page so you can get the name of the form. For instance, the name of my form shows up as “aspnetForm”:
<body id="ctl00_MasterBody" class="mainContentSmall">
<form name="aspnetForm" method="post"
2) At run time, do a “view source” in your page so you can get the name of the control you are interested in. The name of my hidden button shows up as:
<input type="submit" name="ctl00$CPBody$MyHiddenButton" value="" id="ctl00_CPBody_MyHiddenButton" style="border-style:None;VISIBILITY: hidden" />
3) Now that we have the correct names for the form and control
In the code behind of your child page, add the following code to the Page Load event:
private void Page_Load(object sender, System.EventArgs e)
{
this.ClientScript.RegisterStartupScript(GetType(), "MyScriptName", "<script language=JavaScript>document.forms['aspnetForm']['ctl00_CPBody_MyHiddenButton'].click();</script>");
}
That’s it. Give it a try and you’ll see your script being executed at run time.
No comments:
Post a Comment