Call Javascript function from codebehind C#

2008-04-30


How to call a javascript function from ASPX.cs code behind file?

Set the Body tag in your page/master page to runat="server" and an id="MainBody".

Put the script tag in your page like you normally would with any HTML file <script src="popup.js"  type="text/javascript"></script>

Then in the code behind attach the onload attribute to the body tag .

protected void Page_Load(object sender, EventArgs e) { MasterPageBodyTag = (HtmlGenericControl)Page.Master.FindControl("MainBody"); MasterPageBodyTag.Attributes.Add("Onload", "Popup()"); }

Or if you are using Master Pages where the body tag is in the Master Page. but only some of the content pages need to use the javascript.

You put this is the content pages that use the javascript.

protected void Page_Load(object sender, EventArgs e) { MasterPageBodyTag = (HtmlGenericControl)Page.Master.FindControl("MainBody"); MasterPageBodyTag.Attributes.Add("Onload", "Popup()"); }