Using JavaScript in ASP.NET 2005

In ASP.NET V2003 you could have your server side code send JavaScript to, and execute it on, the client using the Page.RegisterStartupScript and Page.RegisterClientScriptBlock methods as shown in my Client-Side JavaScript page. In ASP.NET 2005, these methods were deprecated in favor of the Page.ClientScript.RegisterStartupScript and Page.ClientScript.RegisterClientScriptBlock methods.

Page.ClientScript.RegisterClientScriptBlock
The Page.ClientScript.RegisterClientScriptBlock method lets you place JavaScript at the top of the page which is useful if you want to create a function accessible to the entire page.

For example, place this HTML button in the page's markup:

  <input id="Button1" type="button" value="Hello" onclick="Hello();"/>

This C# server code can tell the button to run the Hello() JavaScript function when the button is clicked:

  protected void Page_Load(object sender, EventArgs e)
  {
     string myHello = @"function Hello() { alert('Hello'); }";

     // See if the script is already registered.
     if (!Page.ClientScript.IsClientScriptBlockRegistered)
     {
       // The optional last parameter tells .NET to surround the 
       // script with <script> tags.
       Page.ClientScript.RegisterClientScriptBlock(this.GetType(),"myHello", 
                     myHello, true);
     }
  }

The rendered HTML and JavaScript will look like:

  <html>
  <head>. . .</head>
  <body>
    <form name="form1" method="post" action="Default.aspx" id="form1">

    <script type="text/javascript">
    <!--
    function Hello() { alert('Hello'); }// -->
    </script>

    <input id="Button1" type="button" value="Hello"  onclick="Hello();"/>
  </form>
  </body>
  </html>

Page.ClientScript.RegisterStartupScript
The Page.ClientScript.RegisterStartupScript method lets you add JavaScript to the bottom of the page. Say your page has a dropdown on it that uses the first value as the default selection and you want to display a message showing what the selection is when the page loads. Here is the page's markup:

<html>
<head>. . .</head>
<body>
  <form name="form1" method="post" action="Default.aspx" id="form1">

  <asp:DropDownList ID="DropDownList1" runat="server">
    <asp:ListItem Selected='True'>Item 1</asp:ListItem>
    <asp:ListItem>Item 2</asp:ListItem>
    <asp:ListItem>Item 3</asp:ListItem>
  </asp:DropDownList>
</form>
</body>
</html>

And the page's server code:

protected void Page_Load(object sender, EventArgs e)
{
   string myValue = @"alert('Selected value: ' + document.forms[0]['DropDownList1'].value);";

   if (!Page.ClientScript.IsStartupScriptRegistered)
   {
     Page.ClientScript.RegisterStartupScript(this.GetType(), 
        "myValue", myValue, true);
   }
}

When the page loads the user will get an Alert() dialog showing the selected value. This is a simplistic example but the idea is that the JavaScript is using the control's value. If the RegisterClientScriptBlock method was used instead, the JavaScript would have been written to the top of the page and would have executed before the dropdown was defined resulting in an error.

Adding JavaScript to a Control from Server Code
In the first example, button1 was assigned an onClick event in the HTML. I could have tied the JavaScript to it from server code in a couple of ways. If a server control was used instead, the code behind would have access to it:

Server Button Control:

  <asp:Button ID="Button1" runat="server" Text="Hello" />

Server code to bind the JavaScript:

  this.Button1.Attributes.Add("onclick", "javascript:Hello();");

Instead of using a server control, I could have used an HTML control with the runat="server" attribute. .NET 2.0+ can access any markup control provided this attribute is set. The server code remains the same.

   <input id="Button1" type="button" value="Hello" runat="server"/>

Worth noting is the behavior of these two controls. The asp:Button control submit the page back to the server after running the JavaScript whereas the HTML control does not. This can be avoided by adding a return value to the JavaScript in the case of the asp:Button control:

  this.Button1.Attributes.Add("onclick", "javascript:Hello(); return false;");

Page.ClientScript.RegisterClientScriptInclude
Instead of placing your JavaScript inline, it is often better to place it in a .js file and include it in the web page. You do this with the following:

   if (!Page.ClientScript.IsClientScriptIncludeRegistered)
   {
     Page.ClientScript.RegisterClientScriptInclude("myFile", "myJavaScriptFile.js");
   }

which renders the following in the <Head> tag of your web page:

  <script src="myJavaScriptFile.js" type="text/javascript"></script>

To see how to use JavaScript to update parts of a web page asynchronously without posting back and refreshing the entire page, see my AJAX Tutorial and my Client Side Javascript page to see how ASP.NET 2005 implements AJAX.


About TheScarms
About TheScarms


Sample code
version info

If you use this code, please mention "www.TheScarms.com"

Email this page


© Copyright 2016 TheScarms
Goto top of page