Wednesday, July 29, 2009

Call JavaScript function from C#

Following describes the steps to call a javascript from C# code:
Let us assume that javascript function is residing in an external javascript file, then follow below steps:

Step1: Register the javascript file

this.Page.ClientScript.RegisterClientScriptInclude(this.GetType(), "NewsWebPart.js", siteCollectionRootUrl + "_LAYOUTS/Monsanto/MPS/NewsWebPart/js/NewsWebPart.js");

You can check the syntax for RegisterClientScriptInclude in .NET API.

Step2: Create HTML Generic Control for script tag and add attribute values.
HtmlGenericControl inlineScript = new HtmlGenericControl("script");
inlineScript.Attributes.Add("type", "text/javascript");
inlineScript.Attributes.Add("language", "javascript");


Step3: Call the javascript function
inlineScript.InnerHtml = "MakeConnectionRotateRequest("
+ "'" + SourceUrl + "'");";


In the above, you can see the javascript call by including parameter values from C# variables.

Step4: Include the HTML Generic control in the page
this.Controls.Add(inlineScript);

No comments: