Embed client-side JavaScript in an ASP.NET 1.1 web page from server side code

Many times on your web pages you may want to use client side JavaScript to perform validation or provide visual effects. JavaScript can be added to an ASP.NET page within the HTML code or it can be added in the server side code. To have the server side code render the JavaScript in the page, do not use the Response.Write method. Instead use the Page class.

The Page class offers the following methods:

Page.RegisterStartupScript
- adds JavaScript to the web form right before the ending </form> tag

Page.RegisterClientScriptBlock
- adds JavaScript to the web form, right after the <form runat="server"> declaration

Page.IsStartupScriptRegistered
- Determines if the client startup script is registered with the page

Page.IsClientScriptBlockRegistered
- Determines if the client script block is registered with the page

Multiple scripts can be added to a page. Each script uses a key that identifies that specific block of script. The IsStartupScriptRegistered and IsClientScriptBlockRegistered methods determine if a specified script has been registered.

This sample shows how to scroll a control into view and give it focus when the page loads. It also emits a JavaScript function that displays an alert when a button is clicked.

Registering JavaScript should be done in the Page_Load event outside of any conditional Page.IsPostBack logic. Otherwise it will either be available before or after page post backs but not both.

NOTE: For a ASP.NET 2.0 version of this page click here.

VB.NET Example:

Create a Web Form with 3 textboxes and two buttons. Set button1.Text to "Click Me" and button2.Text to "Alert". Place textbox3 way down at the bottom of the page so it will not be visible until you scroll the browser window.

Add this code to the Page_Load event:

    If Not Page.IsStartupScriptRegistered("ScrollToControl") Then
        ScrollToControl(TextBox3)
    End If

    If Not Page.IsClientScriptBlockRegistered("ShowAlert") Then
        ShowAlert("Hello")
    End If

    Me.Button2.Attributes.Add("onClick", "return showAlert()")

    If Page.IsPostBack Then
        '...
    End If

Add this code to scroll to the textbox and give it focus:

    Public Sub ScrollToControl(ByVal ctl As Control)
        Dim script As New System.Text.StringBuilder
        Dim clientID As String = ctl.ClientID

        script.Append("<script language='javascript'>")
        script.Append("try {")
        script.Append("document.getElementById('" & clientID & "').scrollIntoView();")
        script.Append("document.getElementById('" & clientID & "').focus();")
        script.Append("} catch (e) {}")
        script.Append("</script>")

        RegisterStartupScript("setScrollAndFocus", script.ToString())

    End Sub

Add this code to show an alert when button 2 is clicked:

    Public Sub ShowAlert(ByVal msg As String)
        Dim script As New System.Text.StringBuilder

        script.Append("<script language='javascript'>")
        script.Append("function showAlert() {")
        script.Append("alert('" & msg & "'); ")
        script.Append("return false; }")
        script.Append("</script>")

        RegisterClientScriptBlock("ShowAlert", script.ToString())

    End Sub

When you run the code, right click the browser window, and "view source", the rendered HTML should look something like this. Note the emitted JavaScript.

<body ...>
  <form name="Form1" method="post" action="WebForm1.aspx" id="Form1">
  <input type="hidden" name="__VIEWSTATE" value="..." />

  <script language='javascript'>function showAlert() {alert('Hello'); return false; }</script>

  <input name="TextBox1" type="text" id="TextBox1" style="height:20px; ..." />
  
  <input type="submit" name="Button2" value="Alert" 
         id="Button2" onClick="return showAlert()" style="..."/>
  <input name="TextBox3" type="text" id="TextBox3" style="height:20px;  ..." />
  <input name="TextBox2" type="text" id="TextBox2" style="height:20px;  ..." />  
  <input type="submit" name="Button1" 
          value="Click Me" id="Button1" style="LEFT: 358px; ..." />

  <script language='javascript'>try {document.getElementById('TextBox3').scrollIntoView();
           document.getElementById('TextBox3').focus();} catch (e) {}</script>
  </form>
</body>




About TheScarms
About TheScarms


Sample code
version info

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

Email this page


© Copyright 2024 TheScarms
Goto top of page