Embedding Java Scripts in ASP.NET

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


Comments

  • The Secret dominate the nike-market Is Fairly Simple and easy!

    Posted by Acuddence on 05/01/2013 02:16pm

    New questions about nike replied to and why you have to browse through every single statement on this guide.[url=http://www.nikejpgolf.biz/]nike ゴルフ[/url] A decent solid double twist on nike [url=http://www.nikejpgolf.biz/nike-ゴルフボール-c-23.html]ナイキ ボール[/url] Interesting questions on nike replied to and in addition reasons why you need to take a look at each phrase of this specific guide. [url=http://www.nikejpgolf.biz/nike-アイアン-c-1.html]ゴルフ ナイキ[/url] Independent content material divulges Five innovative new things for nike that nobody is mentioning. [url=http://www.nikejpgolf.biz/nike-アイアン-c-1.html]ナイキ[/url] Often the nike Provider Chat - Folks who likes next to nothing wins? [url=http://www.nikejpgolf.biz/nike-ゴルフシューズ-c-15.html]nike air jordan[/url] Focus and formation throughout Irvine - nike actually leaves without good-bye [url=http://www.nikeyasuyi.com/]ナイキ スニーカー[/url] Things and formation in Las Vegas, Nevada - nike has left with no goodbye [url=http://www.nikeyasuyi.com/nikeナイキRunning-c-3.html]ナイキランニング[/url] The nike Corporate Chat - - Those people who cares about nothing is victorious?? [url=http://www.nikeyasuyi.com/nikeナイキDunk-c-9.html]nike dunk[/url] The main nike Endeavor Dialog : Those Who loves pretty much nothing wins? [url=http://www.nikeyasuyi.com/nikeナイキDunk-c-9.html]ナイシューズ[/url] nike will give brand new lifespan to a old subject-- gold classic

    Reply
  • The Actual Key On the way to master the nike-world Is Quite Basic!

    Posted by Acuddence on 04/24/2013 06:25pm

    Interesting queries about nike clarified not to mention the reasons you must definitely read carefully each word on this study.[url=http://www.nikejpgolf.biz/]ゴルフ ナイキ[/url] An actual double twist on nike [url=http://www.nikejpgolf.biz/nike-ゴルフボール-c-23.html]ナイキgolf[/url] New queries about mizuno replied to and reasons why you should certainly read through every single word in this article. [url=http://www.nikejpgolf.biz/nike-アイアン-c-1.html]nike ゴルフ[/url] Honest guide unwraps 5 innovative new things on mizuno that no one is speaking of. [url=http://www.nikejpgolf.biz/nike-アイアン-c-1.html]nike ゴルフ[/url] Their mizuno Business Presentation - - Everyone who loves next to nothing gains all the perks?! [url=http://www.nikejpgolf.biz/nike-ゴルフシューズ-c-15.html]ナイキ nike[/url] Goods and developing in Sin City - mizuno leaves without farewell [url=http://www.nikeyasuyi.com/]nike free[/url] Tools and manufacturing throughout The philipines : mizuno leaves without goodbye [url=http://www.nikeyasuyi.com/nikeナイキRunning-c-3.html]ナイキ ランニングシューズ[/url] Some of the nike Organisation Dialogue - And so, who cares for zilch revenues?! [url=http://www.nikeyasuyi.com/nikeナイキDunk-c-9.html]ナイシューズ[/url] Their nike Corporate Meet - Consequently, who cares about nothing benefits? [url=http://www.nikeyasuyi.com/nikeナイキDunk-c-9.html]ナイシューズ[/url] nike adds all new life span to an old matter-- defacto popular

    Reply
  • Appreciation

    Posted by clsantosh on 06/28/2007 04:42am

    Hi Gayan, Good Research! Keep it up!

    Reply
  • how to control the position

    Posted by Legacy on 10/03/2003 12:00am

    Originally posted by: alan

    Your sample is great.
    When I want to embed a chart graph that created by javascript object, I wonder how to contorl the embeding position in web page.
    Thanks

    Reply
  • EmbeddingJava.html

    Posted by Legacy on 08/14/2003 12:00am

    Originally posted by: Stephen McFall

    Excellent - only decent example showing how to do this I've been able to find.

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • On-demand Event Event Date: September 10, 2014 Modern mobile applications connect systems-of-engagement (mobile apps) with systems-of-record (traditional IT) to deliver new and innovative business value. But the lifecycle for development of mobile apps is also new and different. Emerging trends in mobile development call for faster delivery of incremental features, coupled with feedback from the users of the app "in the wild." This loop of continuous delivery and continuous feedback is how the best mobile …

  • The explosion in mobile devices and applications has generated a great deal of interest in APIs. Today's businesses are under increased pressure to make it easy to build apps, supply tools to help developers work more quickly, and deploy operational analytics so they can track users, developers, application performance, and more. Apigee Edge provides comprehensive API delivery tools and both operational and business-level analytics in an integrated platform. It is available as on-premise software or through …

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds