Embedding Java Scripts in ASP.NET

CodeGuru content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Environment: ASP.NET, C#, JavaScript

Developers use the flexibility of writing JavaScript to achieve the functionality they need in ASP.NET. For an example, the can use it to create a popup window for some reason. There are two ways that a developer can write these codes in a web page. Either write it in .aspx page HTML section, or write at .cs file and register them. (I am of course concentrating on developing C# .NET applications.) In this article, I look at how can a developer can write and register his scripts in a Web application and what methods are available in the .NET environment to achieve this.

The easiest and most popular way of writing the script is to simply write it in an HTML section, as displayed below.


<HTML>
<HEAD>
<title>WebForm1</title>
<script language=”javascript”>
function pop_window()
{
var confirmWin = null;
confirmWin = window.open(‘PopUpWindow.aspx’,’anycontent’,
‘width=455,height=435,status’);
}
</script>
</HEAD>
<body>
<form name=”Form1″ method=”post” action=”WebForm1.aspx”
id=”Form1″>
<input type=”button” onClick=”pop_window()” value=”Open Window”>
</form>
</body>
</HTML>

The preceding JavaScript simply displays the PopUpWindow.aspx page in a popup window (EmbeddingJava3.zip).

This looks very simple and perfect. But, try to imagine a situation in which you need to make this popup window pop up in a number of different pages. For example, take this popup window as a spell checker window and all the pages in the ASP.NET application need to be spellchecked. As a developer, you have the option of cutting and pasting the above script to each page in the Web application, or simply isolate the script to a simple class file and register it every time that’s necessary.

There are two methods available to register a script in .NET environment. They are RegisterStartupScript and RegisterClientScriptBlock.

RegisterStartupScript

This method takes two parameters:

RegisterStartupScript (string Key, string script).

Key is the unique key that identifies a script block and script is the content of the script that will be sent to the client. This method will embed the script just before the closing tag of the page object’s <form runat=”server” > element as displayed below.

I am using an example (EmbeddingJava1.zip) that generates a popup window when you click a button and pass a value from the popup window to the main window. Following is the outcome, in HTML format, after registering the scripts.


<!DOCTYPE HTML PUBLIC “-//W3C//DTD HTML 4.0 Transitional//EN” >
<HTML>
<HEAD>
<title>WebForm1</title>
</HEAD>
<body MS_POSITIONING=”GridLayout”>
<form name=”Form1″ method=”post” action=”WebForm1.aspx”
id=”Form1″
>

<input type=”submit” name=”Button1″ value=”Submit” id=”Button1″
style=”Z-INDEX: 101; LEFT: 171px; POSITION: absolute;
TOP: 72px” />
<textarea name=”TextBox1″ id=”TextBox1″
style=”height:109px;Z-INDEX: 102;LEFT: 110px;
POSITION: absolute; TOP: 117px”></textarea>

<input type=”submit” name=”Button2″ value=”Button” id=”Button2″
style=”Z-INDEX: 103; LEFT: 99px; POSITION: absolute;
TOP: 285px” />

<script language=JavaScript id=’PopupWindow’>
var confirmWin = null;
confirmWin = window.open(‘PopUpWindow.aspx’,’anycontent’,
‘width=455,height=435,status’);
if((confirmWin != null) && (confirmWin.opener==null)) {
confirmWin.opener = self;
}
</script>

<script language=JavaScript id=’ParentLoad’>
function addOption(strValue){
var objForm = document.forms[‘Form1’];
var objFormField = objForm.elements[‘TextBox1’];
if (objFormField != null) objFormField.value = (strValue); }
</script>

</form> //Scripts are embedded at the end of the <form> tag.
</body>
</HTML>

Implementing RegisterStartupScript

You simply need to write the JavaScript as a string and pass the string as the script parameter to the RegisterStartupScript method with a string key. In the following example, I register two JavaScript methods.

PopupWindow method will generate a popup window. I am using Script as the script string and PopupWindow as the key.

The addOption function will display the value pass by popup window. I am using ParentLoadScript as the script string and ParentLoad as the key.


private void Button1_Click(object sender, System.EventArgs e)
{
string PopUpWindowPage = “PopUpWindow.aspx”;

//Script for popup window
string Script = “”;
Script += “n<script language=JavaScript id=’PopupWindow’>n”;
Script += “var confirmWin = null; n”;
Script += “confirmWin = window.open(‘”+PopUpWindowPage+”‘,
‘anycontent’,
‘width=455,height=435,
status’); n”;

Script += “if((confirmWin != null) && (confirmWin.opener==null))
{ n”;
Script += ” confirmWin.opener = self; n”;
Script += “}n”;
Script += “</script>”;

//Script for displaying popup window information in main window
string ParentLoadScript = “”;
ParentLoadScript += “n<script language=JavaScript
id=’ParentLoad’>n”;
ParentLoadScript += “function addOption(strValue){ n”;
ParentLoadScript += “var objForm = document.forms[‘Form1’];n”;
ParentLoadScript += “var objFormField =
objForm.elements[‘TextBox1’];n”;
//ParentLoadScript +=”alert(objFormField);n”;
ParentLoadScript += ” if (objFormField != null)
objFormField.value = (strValue); }n”;
ParentLoadScript += “</script>”;

//Check whether they are already registered
if(!this.IsStartupScriptRegistered(“PopupWindow”))
{
//Register the script
this.RegisterStartupScript(“PopupWindow”,Script);
}
//Check whether they are already registered
if(!this.IsStartupScriptRegistered(“ParentLoad”))
{
//Register the script
this.RegisterStartupScript(“ParentLoad”,ParentLoadScript);
}
}

Before I register the script, I have a conditional if statement, IsStartupScriptRegistered. Calling this method will avoid unnecessary assembling of the client-side script. This is very important if the script requires a large amount of server resources.

IsStartupScriptRegistered(string key)

Key is the string key of the start-up script to search for. This methods will simply checked wether this script is already registered or not. Only if not registered, it will allow registering the script. Multiple script blocks with same key is considered as duplicates.

RegisterClientScriptBlock

This method takes two parameters.

RegisterClientScriptBlock (string Key, string script)

Key is the unique key that identifies a script block and script is the content of script that will be sent to the client. This method will embed the script just after the opening tag of the page object’s <form runat=”server” > element as displayed below.

I am using an example (EmbeddingJava4.zip) that generates a popup window when you click a button and passing a value from popup window to main window. Following is the outcome in HTML format after registering the scripts.

<HTML>
<HEAD>
</HEAD>
<body MS_POSITIONING="GridLayout">
  <form name="Form1" method="post" action="WebForm1.aspx"
        id="Form1">    //Scripts are embedded at the beginning
                       //of the </form> tag.

  <script language=JavaScript id='PopupWindow'>
  var confirmWin = null;
  confirmWin =  window.open('PopUpWindow.aspx','anycontent',
                            'width=455,height=435,status');
  if((confirmWin != null) && (confirmWin.opener==null)) {
      confirmWin.opener = self;
  }
  </script>


  <script language=JavaScript id='ParentLoad'>
  function addOption(strValue){
  var objForm       = document.forms['Form1'];
  var objFormField  = objForm.elements['TextBox1'];
  if (objFormField != null) objFormField.value = (strValue); }
  </script>


  <input type="submit" name="Button1" value="Submit" id="Button1"
         style="Z-INDEX: 101; LEFT: 171px; POSITION: absolute;
                              TOP: 72px" />
  <textarea name="TextBox1" id="TextBox1"
            style="height:109px;Z-INDEX: 102; LEFT: 110px;
                                POSITION: absolute;
                                TOP: 117px"></textarea>
  <input type="submit" name="Button2" value="Button" id="Button2"
  style="Z-INDEX: 103; LEFT: 99px; POSITION: absolute;
                       TOP: 285px" />
  </form>
</body>
</HTML>

Implementing RegisterClientScriptBlock

This is very similar to using the RegisterStartupScript method. You simply need to write the JavaScript as a string and pass the string as the script parameter to the RegisterClientScriptBlock method with a string key. In the following example, I register two JavaScript methods.

Popup Window method will generate a popup window. I am using Script as the script string and PopupWindow as the key.

The addOption function will display the value pass by popup window. I am using ParentLoadScript as the script string and ParentLoad as the key.

private void Button1_Click(object sender, System.EventArgs e)
{
  string PopUpWindowPage = "PopUpWindow.aspx";

  //Script for popup window
  string Script = "";
  Script += "n<script language=JavaScript id='PopupWindow'>n";
  Script += "var confirmWin = null; n";
  Script += "confirmWin = window.open('"+PopUpWindowPage+"',
                                      'anycontent', width=455,
                                       height=435status'); n";

  Script += "if((confirmWin != null) && (confirmWin.opener==null))
      { n";
  Script += "  confirmWin.opener = self; n";
  Script += "}n";
  Script += "</script>";

  //Script for displaying popup window information in main window
  string ParentLoadScript = "";
  ParentLoadScript += "n<script language=JavaScript
                                 id='ParentLoad'>n";
  ParentLoadScript += "function addOption(strValue){ n";
  ParentLoadScript += "var objForm = document.forms['Form1'];n";
  ParentLoadScript += "var objFormField =
                           objForm.elements['TextBox1'];n";
  //ParentLoadScript +="alert(objFormField);n";
  ParentLoadScript += " if (objFormField != null)
  objFormField.value = (strValue); }n";
  ParentLoadScript += "</script>";

  //Check whether they are already registered
  if(!this.IsClientScriptBlockRegistered("PopupWindow"))
  {
    //Register the script
    this.RegisterClientScriptBlock("PopupWindow",Script);
  }
  //Check whether they are already  registered
  if(!this.IsClientScriptBlockRegistered("ParentLoad"))
  {
    //Register the script
    this.RegisterClientScriptBlock("ParentLoad",ParentLoadScript);
  }
}

Before I register the script, I have an if statement, IsClientScriptBlockRegistered. Calling this method will avoid unnecessary assembling of the client-side script. This is very important if the script requires a large amount of server resources.

IsClientScriptBlockRegistered (string key )

Key is the string key of the start-up script to search for. This method will simply check whether this script is already registered or not. Only if it is not registered, it will allow registering the script. Multiple script blocks with same key are considered as duplicates.

The above examples look straightforward and are easy to implement. I see the real advantage of these methods in a situation such as I mentioned earlier, where you need to use the same JavaScript again and again on a number of different Web pages. In example EmbeddingJava2.zip, I look at this situation.

The first thing I do is isolate the JavaScript into a Class file called JavaScriptClass.cs file. Then, I simply pass in the Page object as a parameter of the page on which I need to register the JavaScript.

public void RegisterScript(System.Web.UI.Page page)
{
  string spellCheckerPage = "PopUpWindow.aspx";

  //Script for popup window
  string Script = "";
  Script += "n<script language=JavaScript id='PopupWindow'>n";
  Script += "var confirmWin = null; n";

  Script += "confirmWin = window.open(' "+ spellCheckerPage+"',
                                      'anycontent','width=455,
                                       height=435,status'); n";

  Script += "if((confirmWin != null) && (confirmWin.opener==null))
            { n";
  Script += "  confirmWin.opener = self; n";
  Script += "}n";
  Script += "</script>";

  //Script for displaying popup window information in main window
  string ParentLoadScript = "";
  ParentLoadScript += "n<script language=JavaScript
                                 id='ParentLoad'>n";
  ParentLoadScript += "function addOption(strValue){ n";
  ParentLoadScript += "var objForm = document.forms['Form1'];n";
  ParentLoadScript += "var objFormField
                    = objForm.elements['TextBox1'];n";
  //ParentLoadScript +="alert(objFormField);n";
  ParentLoadScript += " if (objFormField != null)
  objFormField.value = (strValue); }n";
  ParentLoadScript += "</script>";

  //Check whether they are already registered
  if(!page.IsStartupScriptRegistered("PopupWindow"))
  {
  //Register the script
    page.RegisterStartupScript("PopupWindow",Script);
  }
  //Check whether they are already registered
  if(!page.IsStartupScriptRegistered("ParentLoad"))
  {
    //Register the script
    page.RegisterStartupScript("ParentLoad",ParentLoadScript);
  }
}

On the rest of the pages that need to call the JavaScript, I simply call the RegisterScript function and pass the current page object as an input parameter as displayed below.

private void Button1_Click(object sender, System.EventArgs e)
{
  page1JavaScriptClass = new JavaScriptClass();

  //Call the JavaScript Function
  page1JavaScriptClass.RegisterScript(this);
}

Conclusion

As you can see, it ends up in only one line of code. This makes things easier to maintain and makes it easy to implement in a large Web application without have to write duplicate code. I hope above details will help you in .NET application development.

About the Author

Gayan Peiris is an ASP.NET Developer for the Department of Employment and Workplace Relations in Canberra, Australia. He has designed and developed Microsoft Web and Windows solutions since 1999. His expertise lies in developing scalable, high-performance Web and Windows solutions. His core skills are ADO.NET, ASP.NET, C #, VB.NET, Web Services, XML, Ibuyspy Portals, DNA, and SQL Server. He can be reached at www.gayanpeiris.com.

Downloads

Download demo project EmbeddingJava1.zip – 20 Kb

Download demo project EmbeddingJava2.zip – 26 Kb

Download demo project EmbeddingJava3.zip – 18 Kb

Download demo project EmbeddingJava4.zip – 19 Kb

More by Author

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Must Read