C# Tutorial: Calling Javascript from the Code Behind (.cs) File

In this short tutorial, I will show you how you can call Javascript from your code behind (.cs) file when programming in C#.  It came about because I was trying to find a way to display content in a new window after clicking a button.  So here it is.  (Please note that I am using Visual Studio 2012 and the ASP.NET 4.5 Framework in my examples.)

First, open a new project in Visual Studio by navigating to File -> New -> Project… (or hit Ctrl+Shift+N).

Visual Studio New Project

Next, I will select Templates -> Visual C# -> Web -> ASP.NET Empty Web Application and name the project SampleCode.  I will also check the option to Create a directory for solution and hit the OK button to continue.

SampleCode Project

Now, I am going to add the App_Code folder to my project because I want to create a helper class for organization reasons.  To add this folder, right click on the project name (SampleCode) in the Solution Explorer window and navigate to Add -> Add ASP.NET Folder -> App_Code.

App_Code Folder

To add the class, right click on the App_Code folder you’ve just created and navigate to Add -> Class…  I’ll go ahead and name this class BrowserUtility.cs and click on the Add button.

BrowserUtility Class

To make sure this class gets compiled into an assembly that I can use later, I’ll highlight the BrowserUtility.cs file under the App_Code folder, and in the Properties window, I will change the Build Action from Content to Compile.

Compile Option

In the class itself, I will import the System.Text namespace so that I can use the Stringbuilder class to create my Javascript string.  My class will just contain one public static method called OpenInNewBrowserWindow which takes one string as a parameter and returns a string as a result.  Here’s what the code looks like:

using System;
using System.Collections.Generic;
using System.Text;
using System.Web;

namespace SampleCode.App_Code
{
  public class BrowserUtility
  {
    #region Methods
    public static String OpenInNewBrowserWindow(String url)
    {
      StringBuilder sb = new StringBuilder();
      sb.Append("<script type = 'text/javascript'>");
      sb.Append("window.open('");
      sb.Append(url);
      sb.Append("','','width=1024,height=768')");
      sb.Append("</script>");

      return sb.ToString();
    }
    #endregion
  }
}

Now, I will add an ASP.NET Web Form page to my project by right clicking the project name and selecting Add -> Web Form.  In the Specify Name of Item window, I will type in Default and then click on the OK button.

Specify Name of Item Window

This will create a Default.aspx page.  Double click it to load it in your Visual Studio IDE and then switch to Design View.  Drag a button control onto the page, set the text to something like “Open Page“, and set the ID of the button to something like “openPageButton” if you’d like.  Following the same steps above, create another Web Form page called “HelloWorld” and type in “Hello World!” on the page.  Switch back to the Default.aspx page and double click on the openPageButton button to create a button Click event.  This will open the Default.aspx.cs (code behind) file and create a method called protected void openPageButton_Click(object sender, EventArgs e).  On top, place a using statement to load your custom assembly (i.e. using SampleCode.App_Code) and place the following code within this method:

String newWindow = BrowserUtility.OpenInNewBrowserWindow("HelloWorld.aspx");
ClientScript.RegisterStartupScript(this.GetType(), "script", newWindow);

The ClientScript.RegisterStartupScript method will allow you to execute your Javascript code and can be used for other types of scripts as well.  You entire code behind file should look something like this:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

using SampleCode.App_Code;

namespace SampleCode
{
  public partial class Default : System.Web.UI.Page
  {
    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void openPageButton_Click(object sender, EventArgs e)
    {
      String newWindow = BrowserUtility.OpenInNewBrowserWindow("HelloWorld.aspx");
      ClientScript.RegisterStartupScript(this.GetType(), "script", newWindow);
    }
  }
}

Finish building your application by navigating to Build -> Build Solution or hit Ctrl+Shift+B.  Redirect focus to the Default.aspx window and then hit F5 to launch and test your application.  Make sure you disable any pop-up blockers when you click on the “Open Page” button, and you can see your Javascript working in action.