oreilly.comSafari Books Online.Conferences.


AddThis Social Bookmark Button

Enhancing ASP.NET Pages with JavaScript

by Matthew MacDonald, coauthor of ASP.NET in a Nutshell, 2nd Edition
Use ClickOnce to Deploy Windows Applications

ASP.NET is a server-based platform, which means the code you write executes on the web server instead of in the client's browser. This approach ensures that your code is kept secure from prying eyes, and it sidesteps most browser-compatibility issues. However, it also introduces some unavoidable limitations.

For example, the ASP.NET web page model doesn't provide any way to react to events, such as a user's mouse movements. In this case, the overhead of sending the page back to the server after every mouse movement would make the web page unworkably slow. Similarly, because your code can't interact directly with the browser, it can't display pop-up windows or manage multiple frames in a frameset in the same way a snippet of client-side JavaScript could.

To compensate for these limitations, ASP.NET developers often need to mix a little JavaScript code into their ASP.NET web pages. This is most commonly the case with custom controls. For example, many menu controls allow the user to browse through multiple menu levels without forcing the page to be posted back to the server every time a new level is shown. (You can find sample menu controls at Microsoft's community site.) Similar techniques are used to ensure that other controls remain rich and responsive, without requiring any work from the web server.

Related Reading

ASP.NET in a Nutshell
By G. Andrew Duthie, Matthew MacDonald

In this article, we'll consider three common tasks that require JavaScript but aren't specific to custom controls. You can use these tricks to quickly solve problems that have no native .NET solution. But first, let's look at what you need to do to use JavaScript in an ASP.NET page.

Inserting JavaScript into an ASP.NET Page

To use JavaScript in an ASP.NET page, you first need to take two steps:

  1. Define the script block that contains the JavaScript function. You can add this directly to the HTML of the page, but it is usually more flexible to assign the JavaScript code to a string variable and insert it into the rendered page programmatically.
  2. Insert the script block programmatically. To do this, use either the Page.RegisterStartupScript() or the Page.RegisterClientScriptBlock() method. In the first case, the JavaScript code will execute immediately the next time the page is posted back. In the latter case, the JavaScript code will not execute unless you connect the client-side event of another control to the JavaScript function. In this article, we'll use the first approach.

The next three sections demonstrate this technique.

  1. Showing a Pop-Up Window

    Pop-up windows, often used for advertisements and promotions, are a hallmark of the Internet. But ASP.NET doesn't provide any mechanism for showing pop-up windows, because your code can't interact directly with the client's browser. The only solution is to use JavaScript, which provides the useful function.

    The function requires three parameters:
    • The link for the new page.
    • The frame name of the window.
    • A comma-separated string of attributes that will configure the style and size of the pop-up window. These can include the height and width attributes (with pixel values); the toolbar, menuBar, and scrollbar attributes (set to yes or no, depending on whether you want to display these elements); and the resizable attribute (set to yes or no, depending on whether you want a fixed or resizable window border).

    The following C# code defines the JavaScript code for showing the PopUp.aspx web page in a new window, and registers it to execute immediately upon the page being posted back the next time.

    string popupScript = "<script language='javascript'>" +
      "'PopUp.aspx', 'CustomPopUp', " +
      "'width=200, height=200, menubar=yes, resizable=no')" +
    Page.RegisterStartupScript("PopupScript", popupScript);

    In VB .NET, the code is virtually identical:

    Dim popupScript As String = "<script language='javascript'>" & _
      "'PopUp.aspx', 'CustomPopUp', " & _
      "'width=200, height=200, menubar=yes, resizable=no')" & _
    Page.RegisterStartupScript("PopupScript", popupScript)

    You can use this code in any event handler. For example, you might want the window to appear when the page first loads, or after the user clicks a button or performs another action. In any case, the pop-up window will only appear the next time the page is returned to the user. If you want it to reappear the next time the user takes an action, you'll need to create and register the script block again.

    Note that when the script block is added to the page, it's identified with a descriptive name (in this case, "PopupScript"). If you add a script block with the same name multiple times, it will only be added to the page once.

  2. Changing Control Focus

    The ASP.NET web controls provide a TabIndex property, but this property only applies to Internet Explorer and can't be used to programmatically set the focus to a control of your choice. To perform this task, you'll need the help of some JavaScript code. In this case, you need to find the JavaScript object that corresponds to the control, and call its focus() method.

    The easiest way to handle this task is to create a function that accepts a control, extracts its client-side ID, and uses it to generate the JavaScript function required to set the focus to that control. You can then register this function so it will set the focus the next time the next time the page is sent to the user.

    Here's the function you will need in C#:

    private void SetFocus(Control ctrl)
        // Define the JavaScript function for the specified control.
        string focusScript = "<script language='javascript'>" +
            "document.getElementById('" + ctrl.ClientID +
        // Add the JavaScript code to the page.
        Page.RegisterStartupScript("FocusScript", focusScript);

    Here's the same function rewritten for VB .NET:

    Private Sub SetFocus(ByVal ctrl As Control)
        ' Define the JavaScript function for the specified control.
        Dim focusScript As String = "<script language='javascript'>" & _
          "document.getElementById('" + ctrl.ClientID & _
        ' Add the JavaScript code to the page.
        Page.RegisterStartupScript("FocusScript", focusScript)
    End Sub

    You can now call the custom SetFocus() function from any event handler to change the control focus as needed:


    Remember, the focus change won't take effect until the page is rendered and sent back to the browser.

  3. Handling Frame Navigation

    Frames allow you to display more than one HTML document in the same browser window. In the case of a site with a navigational menu, you could split the page vertically into two frames. The frame on the left would contain the navigation control, while the frame on the right would show the selected content. (For more information about frames, refer to this HTML Frames tutorial or this Web Authoring FAQ.)

    Because frames only exist on the client side, it's a little more work to manipulate them in your ASP.NET code. You need to explicitly select the frame you want to modify, and then assign a new location (URL) to it. The following VB .NET code snippet registers the JavaScript coded needed to change frame 1 to a new page. You can assume that this code will run in the page inside of frame 0.

    Dim url As String = "NewPage.aspx"
    ' Use JavaScript to trigger the redirect in the other window.
    Dim frameScript As String = "<script language='javascript'>" & _
      "window.parent.frames(1).location='" & Url & "';</script>"
    Page.RegisterStartupScript("FrameScript", frameScript)

    The C# code is virtually identical:

    string url = "NewPage.aspx";
    // Use JavaScript to trigger the redirect in the other window.
    string frameScript = "<script language='javascript'>" +
      "window.parent.frames(1).location='" + url + "';</script>"
    Page.RegisterStartupScript("FrameScript", frameScript);


A sprinkling of JavaScript code can enhance the reach and responsiveness of your ASP.NET web pages. Best of all, you don't need to sacrifice ASP.NET's secure, server- based model for the bulk of your coding; just fill in the gaps with a little dash of client-side magic.

Matthew MacDonald is a developer, author, and educator in all things Visual Basic and .NET. He's worked with Visual Basic and ASP since their initial versions, and written over a dozen books on the subject, including The Book of VB .NET (No Starch Press) and Visual Basic 2005: A Developer's Notebook (O'Reilly). His web site is

O'Reilly & Associates recently released (August 2003) ASP.NET in a Nutshell, 2nd Edition.

Return to