Passing Values from Server Code to Client Code

You can use script to pass information from the server to the client. One of the most common ASP.NET questions is how a client-side script can gain access to the values of Session and Application variables. Although there's more than one way to pass server values to the client, the simplest way is to write the values of the server-side variables and assign those values to client-side variables in a script. For example, Listing 20.4 shows how to assign Session.SessioniD to a variable in a client-side script.

Listing 20.4: Transferring Server-Side Variables to Client-Side Scripts (ch20-3.aspx.cs)

private void Page Load(object sender, System.EventArgs e) { String s = "<script language=JavaScript>";

Response.Write("When you load this page, you'll see an alert containing your SessionlD.");

s += "var sessionID='" + Session.SessioniD + "';" +

System.Environment.NewLine; s += "alert('Your SessionID is: ' + sessionID);"; s += "</script>";

RegisterClientScriptBlock("script1", s);

Another way to write a client-side script is to use the Page object's RegisterClientScriptBlock method. The method accepts two arguments: a String object containing an identifying String key for the script and a second String object containing the script code, including the opening and closing

When this code executes, it adds the following script to the browser (although not formatted in quite this way, and with the client's SessionID rather than the one shown below):

<script language=JavaScript>

var sessionID='dzlgjyuuxar342ncewfex545'; alert('Your SessionID is: ' + sessionID); </script>

Here's how it works. On the server, the code in the Page_Load event writes the value of the Session.SessionID to the client-side script string. The call to the RegisterClientScriptBlock method writes the script to the output immediately after the hidden_viewstate control. The browser parses the page and passes the script to the scripting engine, which compiles the script and then displays the alert.

A similar Page class method called RegisterStartupScript inserts a client script at the end of the default form, just before the closing </form> tag. For both the RegisterClientScriptBlock and the RegisterStartupScript methods, you can use the key parameter to avoid inserting duplicate scripts. For example, if you had two custom server controls that shared a client-side script, you wouldn't want to insert two copies. Similarly, if you had a shared server method that registered a script and the method might be called multiple times, you would need to prevent VS from generating multiple script copies. Using the key value, you can test to see if a script is already registered:

if (!Me.IsClientScriptBlockRegistered("yourScriptKeyHere")) { // register the script using Me.RegisterClientScriptBlock

or if (!Me.IsClientStartupScriptRegistered("yourScriptKeyHere")) { //register the script using Me.RegisterClientStartupScript

You can use client-side script transparently to force the browser to request other pages, to submit forms, or to display alternate content. For example, suppose you want to display different pages based on the client's screen resolution. The Request.Browser class gives you the capability to determine which browser a client is using and which scripting engine the browser supports, but it doesn't provide the client's screen resolution. You can work around that problem by writing a client-side script to obtain the screen resolution and send it back to your ASP program.

Note When you write client-side script from within an inline server code block, you have to break up the <script> tags to avoid errors, as you saw earlier in this chapter. However, when you write script from a code-behind code method, you have no such restriction. That's because the ASP.NET engine does not have to parse the code-behind class code for HTML.

Listing 20.5 uses a script written (purposely) in VBScript to determine the screen resolution width and height; it displays that information using the VBScript MsgBox function and then directs the browser back to the originating ASP page with the screen resolution information embedded in the query string data. The server retrieves the screen resolution from the Request.QueryString and then writes it to the screen.

Listing 20.5: Obtaining the Screen Resolution of the Client Computer (ch20-4.aspx.cs)

private void Page Load(object sender, System.EventArgs e) { String s = null;

if (Request.QueryString["Width"] != null) {

Response.Write("Your screen resolution is: " + Request.QueryString["Width"] + "x" + Request.QueryString["Height"] + "<br>"); Response.End();

s = "<script language=VBScript>" + System.Environment.NewLine;

s += " " + "Dim x,y" + System.Environment.NewLine;

s += " " + "x=window.screen.width" +


s += " " + "y=window.screen.height" +


s += " if MsgBox('Your screen resolution is: ' & x & ', ' & y, " +

"vbOkCancel ,'Screen Resolution') = vbOK Then" + System.Environment.NewLine; s += " window.location.href='ch2 0-4.aspx?Width=' & x & " +

"'&Height=' & y" + System.Environment.NewLine; s += " end if" + System.Environment.NewLine; s += "</script>"; s = s.Replace( , "\"");

RegisterClientScriptBlock("script1", s);

The script first tests to see if the Request.QueryString("ScreenWidth") variable has a value. If not, it writes a client-side script to obtain the screen dimensions. The client side script (formatted) looks like this:

<script language=VBScript> Dim x,y x=window.screen.width y=window.screen.height if MsgBox("Your screen resolution is: " & x & ", " & y, vbOkCancel ,"Screen Resolution") = vbOK Then window.location.href="ch20-4.aspx?Width=" & x & "&Height="

The script obtains the browser screen width and height and assigns them to the x and y variables, respectively. Next, it displays a VBScript message box. VBScript message boxes are more flexible than JavaScript alerts because you can control the number and content of buttons and display a title (see Figure 20.2), whereas JavaScript alerts have no programmable title or button control capabilities. In addition, VBScript's MsgBox function returns a value indicating which button the user clicked, which can be extremely useful. VBScript contains built-in constants for the buttons. This example uses the constant vbOKCancel, which displays OK and Cancel buttons. The example also checks the return value to see if the user clicked the OK button, using the vbOK constant.

Figure 20.2: VBScript message boxes are more flexible than JavaScript alerts

When the user clicks the OK button, the script formats a URL containing Width and Height query string values and then sets the document.location.href property. The document.location object has properties containing information about the browser's location. For example:

window.location.href="ch2 0-4.aspx?Width=" & x & "&Height=" & y

Figure 20.2: VBScript message boxes are more flexible than JavaScript alerts

When the user clicks the OK button, the script formats a URL containing Width and Height query string values and then sets the document.location.href property. The document.location object has properties containing information about the browser's location. For example:

window.location.href="ch2 0-4.aspx?Width=" & x & "&Height=" & y

Setting the document.location.href property causes the browser to load the requested document. In this case, setting the property reloads the same page.

The rest of the line appends the page request with the screen width and height that the script obtained from the Screen object to create a URL. After concatenation, the URL looks like this (of course, your resolution may be different):


When the browser submits the request to the server, the ASP.NET engine populates the QueryString collection with the query string key/value pairs appended to the URL—in this case, Width=8 0 0 and Height=600.

The Page_Load event checks the Request.QueryString("Width") variable. When it has a value, the other portion of the form must have been sent to the browser already; therefore, the server-side code displays the user's screen resolution and exits; otherwise it writes the script, causing the browser to display the message box.

The most important point to remember from this example is that you can use client script to perform some action on the client and immediately return that information to the server—without the user seeing anything. For example, if you suppress the MsgBox call by deleting it or commenting it out, you'll see that, to the user, the request appears to write the screen resolution immediately, when in fact what's happened is an extra round trip. The server responds to the original request with a script that executes and immediately returns the screen resolution values to the server, which then responds with some visible information. You can use this technique in many ways.

For example, suppose you have two sites, both secured and running on different servers in different domains: and Whenever a user successfully logs on to one of those sites, you want that browser instance to have seamless access to the other site. After a successful authentication at either site, you set a cookie to prove authentication for future requests to that site. But cookies are domain specific. A browser holding a cookie from Site1 won't send it to Site2. By redirecting the authenticated browser from Site1 to Site2 by submitting a form containing the authentication cookie to Site2, that site can set its own cookie and redirect the browser back to Site1. You can use the concepts shown in this section—of client-side code that executes automatically behind the scenes—to do exactly that.

Was this article helpful?

0 0

Post a comment