Using VS - DevSource
DevSource: Microsoft Developer Resource DevSource Home Sponsored by Microsoft Home Add Ons Architecture Languages Techniques Using VS Forums
Home arrow Using VS arrow Page 4 - Working with Scripts and Master Pages
Working with Scripts and Master Pages
By John Mueller

Rate This Article: Add This Article To:

Working with Scripts and Master Pages - ' Handling Body Tags '
( Page 4 of 4 )

Handling <body onload="PageLoad()"> Scripts

Most developers are aware of how to use the <body> tag's onload event to execute a script when the page loads. Unfortunately, this technique doesn't work when you're working with master pages, because you don't have access to the <body> tag. An alternative used by many developers at this point is to add the script without a function name directly after the <body> tag. Unfortunately, using this approach will result in an error message when working with a master page-the script won't execute.

ADVERTISEMENT

Fortunately, you do have an alternative that does work with master pages. You must inject the script into the Web page using the ASPX page Load() event. What you'll do is create the script in the event handler, and then add it to the Web page indirectly. One trick that you might want to use, when employing this technique, is to test the script on a standalone page before you try to recreate it in the production page. It's usually easier to build and test the script using a standard Web page than to create it in an ASPX page. Once you perfect the script, you can move it to the code behind page.

The script in this example answers a particular need that many Web developers must answer today. Some users don't mind informational popup windows — or at least, they don't mind seeing them one time. This script shows a technique for creating a popup window that contains an opt-out checkbox, as shown in Figure 3.

Figure 3: Many developers now add an opt out feature to popup windows to reduce user frustration.

The opt-out feature relies on a local cookie. When the content page detects this cookie, it checks the user's preference and either opens the popup window or keeps it closed. Because this is an informational popup window, it always opens the first time the user visits the Web page.

Listing 1 shows the injection script for the content page. This script performs the cookie detection and popup window display.

Listing 1: Creating an Onload Script

Protected Sub Page_Load(ByVal sender As Object, _
   ByVal e As System.EventArgs) Handles Me.Load

   Dim TheScript As New StringBuilder  ' Holds the injected script.

   ' Create the script.
   TheScript.Append("<script type='text/javascript'>" + vbCrLf)
   TheScript.Append("var  ACookie; // Holds the document cookie.")
   TheScript.Append(vbCrLf)
   TheScript.Append("var  Parsed;  // Holds the split cookies.")
   TheScript.Append(vbCrLf + vbCrLf)
   TheScript.Append("// Get the cookie." + vbCrLf)
   TheScript.Append("ACookie = unescape(document.cookie);")
   TheScript.Append(vbCrLf + vbCrLf)
   TheScript.Append("// Check the cookie status." + vbCrLf)
   TheScript.Append("if (ACookie == '')" + vbCrLf)
   TheScript.Append("   window.open('AddedInfoPopup.ASPX', " + vbCrLf)
   TheScript.Append("               'AddedInfo', " + vbCrLf)
   TheScript.Append("               'height=300, width=400, ")
   TheScript.Append("resizable=true, dependent=true');")
   TheScript.Append(vbCrLf + vbCrLf)
   TheScript.Append("// Split the cookie elements." + vbCrLf)
   TheScript.Append("Parsed = ACookie.split('=');" + vbCrLf + vbCrLf)
   TheScript.Append("// Determine whether the user wants the ")
   TheScript.Append("additional Information" + vbCrLf)
   TheScript.Append("// displayed on screen." + vbCrLf)
   TheScript.Append("if (Parsed[1] == 'false')" + vbCrLf)
   TheScript.Append("   window.open('AddedInfoPopup.ASPX', " + vbCrLf)
   TheScript.Append("               'AddedInfo', " + vbCrLf)
   TheScript.Append("               'height=300, width=400, ")
   TheScript.Append("resizable=true, dependent=true');")
   TheScript.Append(vbCrLf)
   TheScript.Append("</script>")

   ' Add the script to the Web page.
   Me.ClientScript.RegisterStartupScript( _
      GetType(String), "ShowInfoPage", TheScript.ToString())
End Sub

The process is relatively simple. You build up a string containing the script you want to execute. Adding white space is extremely helpful when you start debugging the script, so adding the vbCrLf (carriage return/line feed) constants is necessary. Once you build up a script, you add it to the Web page using the Me.ClientScript.RegisterStartupScript() method. This method accepts three inputs: the data type of the script, the script identifier, and the script content. When you run the script, it looks precisely like a script that you added directly to the Web page. Figure 4 shows the actual source code from the content page.

Figure 4: Injected scripts look like you added them directly to the Web page.

The injected script begins by loading the cookie created by the informational pop-up form. If the cookie is missing, the code automatically displays the popup form, because this is the user's first visit to the Web site. This cookie is normally available because it's permanent and the main page is in the same path as the Web page that created the cookie. After the code loads the cookie, it determines whether the user wants the additional information popup form loaded. If the user wants to see the additional information, the code uses the window.open() method to open the popup window. Notice that this popup form depends on the main page, which means it closes automatically when the user closes the main page.

The informational popup window also requires a script that automatically executes when the main page opens it. Listing 2 shows this script.

Listing 2: Configuring a Page Based on Cookie Settings

Protected Sub Page_Load(ByVal sender As Object, _
   ByVal e As System.EventArgs) Handles Me.Load

   Dim TheScript As New StringBuilder  ' Holds the injected script.

   ' Create the script.
   TheScript.Append("<script type='text/javascript'>" + vbCrLf)
   TheScript.Append("   var  ACookie; // Holds the document cookie.")
   TheScript.Append(vbCrLf)
   TheScript.Append("   var  Parsed;  // Holds the split cookies.")
   TheScript.Append(vbCrLf + vbCrLf)
   TheScript.Append("   // Get the cookie." + vbCrLf)
   TheScript.Append("   ACookie = unescape(document.cookie);")
   TheScript.Append(vbCrLf + vbCrLf)
   TheScript.Append("   // Split the cookie elements." + vbCrLf)
   TheScript.Append("   Parsed = ACookie.split('=');")
   TheScript.Append(vbCrLf + vbCrLf)
   TheScript.Append("   // Determined the checked value." + vbCrLf)
   TheScript.Append("   if (Parsed[1] == 'true')" + vbCrLf)
   TheScript.Append("      __aspnetForm.cbDontShow.checked = true;")
   TheScript.Append(vbCrLf)
   TheScript.Append("   else" + vbCrLf)
   TheScript.Append("      __aspnetForm.cbDontShow.checked = false;")
   TheScript.Append(vbCrLf)
   TheScript.Append("</script>" + vbCrLf)

   ' Add the script to the Web page.
   Me.ClientScript.RegisterStartupScript( _
      GetType(String), "ShowInfoPage", TheScript.ToString())
End Sub

As you can see, the technique for creating the injected script is the same, but the results are different. In this case, the script uses the content of the cookie to configure the form. When the cookie exists and it contains a value of true, the code checks the check box in the form. This script ensures the user sees the true status of the form when the popup displays.

Adding Scripts Directly to Web Pages

You don't have to inject all of the scripts you want on a Web page-only those that will execute when the page loads. Scripts that execute as the result of a button click can appear within the <asp:Content> tag of the content page. For example, when the user clicks the Don't Show checkbox, the popup window must create a cookie expressing the user's selection. You create the connection between the script and the control using an event entry like this:

<label>Don't Show This Window Again</label>
<input id="cbDontShow" 
       type="checkbox" 
       accesskey="S" 
       title="Disables additional information display."
       onclick="cbDontShow_OnClick()" />

Of course, using this approach means mixing standard HTML controls with ASPX controls on the same page. You don't need to worry about using this technique; it works quite well. Fortunately, some ASP.NET controls also allow direct access to client side scripts. For example, the CheckBox control includes the OnClientClick property that you use to assign a client side script. Consequently, either of these controls work equally well for dismissing the popup window.

<input id="btnDismiss" 
       type="button" 
       value="Dismiss" 
       accesskey="D" 
       title="Closes the added information window."
       onclick="btnDismiss_OnClick()" />
<asp:Button ID="btnDismiss2" 
            runat="server" 
            Text="Dismiss" 
            OnClientClick="btnDismiss_OnClick"
            AccessKey="D"
            ToolTip="Closes the added information window." />

The associated script is a standard ASPX Web page script entry. Here's the cookie script.

<script type="text/javascript">
<!--
function cbDontShow_OnClick()
{
    var UserCookie; // Stores the user name.
    var Expire;     // Expiration date.
    
    // Get an expiration date. Set it to expire one year
    // from the current date.
    Expire = GetExpireDate(0, 0, 1);
    
    // Create the username cookie.
    UserCookie = "AddedInfo=" + 
                 escape(aspnetForm.cbDontShow.checked) +
                 "; expires=" + Expire;
    
    // Add the cookie to the document.
    document.cookie = UserCookie;
}
-->
</script>

As you can see, this is a standard Web page script that you add directly to the ASPX page, rather than to the code behind. In this case, the script creates a cookie that expires a year from the current date. Anyone who has written JavaScript will recognize this as something you could find on any HTML page.

Anyone who thinks that scripting is dead hasn't viewed the Web pages that ASP.NET creates. Yes, using code behind makes sense whenever you can to reduce complexity and ensure your application is easy to debug. However, at some point you're going to need the client side processing functionality that scripting can provide, as the automated scripts that ASP.NET generates attest. The example in this article demonstrates just one of many scenarios where scripting on modern Web pages is a must.



 
 
>>> More Using VS Articles          >>> More By John Mueller
 



HD VOIP Has Arrived (with Tony Konstner)

Play Video >

All Videos >

Google and blonde jokes?

Read now >

Favorite books!

Read now >

View Now
DevSource RSS FEEDS
XML Want an easy way to keep up with breaking tech news? And the Get DevSource headlines delivered to your desktop with RSS.