Lesson 3: Navigating Between Forms

Lesson 3: Navigating Between Forms

Linking information is the essence of the Web. In a Web Forms application, hyperlinks and the navigation methods are what link multiple Web forms together into a cohesive application. ASP.NET provides several ways to navigate between pages in your application, and each of these techniques yields different effects in terms of how the page is displayed and how data is exchanged between pages.

In this lesson, you ll learn how to use each of the different navigation techniques in code and in HTML.

After this lesson, you will be able to

  • List different ways to navigate between pages in a Web forms application

  • Choose the appropriate navigation technique based on your programming needs

  • Retain form ViewState data across a request

  • Process a second Web form without leaving the current Web form

  • Display a page in a new browser window and control that window from server code

Estimated lesson time: 35 minutes

Ways to Navigate

ASP.NET provides five distinct ways to navigate between pages in your application, as shown in Table 4-8.

Table 4-8. Navigating Between Pages

Navigation method

Use to

Hyperlink control

Navigate to another page.

Response.Redirect method

Navigate to another page from code. This is equivalent to clicking a hyperlink.

Server.Transfer method

End the current Web form and begin executing a new Web form. This method works only when navigating to a Web Forms page (.aspx).

Server.Execute method

Begin executing a new Web form while still displaying the current Web form. The contents of both forms are combined. This method works only when navigating to a Web Forms page (.aspx).

Window.Open script method

Display a page in a new browser window on the client.

Using Hyperlinks and Redirection

Hyperlink server controls respond to user click events by displaying the page specified in the control s NavigateURL property. The Hyperlink control does not expose any server-side user events; if you want to intercept a click event in code, use the LinkButton control or the ImageButton server control.

To navigate from a LinkButton or ImageButton control, use the Response object s Redirect method, as shown here:

Visual Basic .NET

Private Sub LinkButton1_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles LinkButton1.Click ' Display next page. Response.Redirect("NextPage.aspx") End Sub

Visual C#

private void LinkButton1_Click(object sender, System.EventArgs e) { // Display next page. Response.Redirect("NextPage.aspx"); }

Using the Transfer Method

Using the Transfer method is similar to executing a hyperlink or using the Redirect method, with one difference: Transfer can retain some information from the source page across requests. Setting the Transfer method s preserveForm argument to True makes the form s QueryString, ViewState, and event procedure information available in the destination form.

To be able to read one Web form s ViewState from another, you must first set the EnableViewStateMac attribute in the Web form s Page directive to False. By default, ASP.NET hashes ViewState information, and setting this attribute to False disables that hashing so that the information can be read on the subsequent Web form. The following line shows how to disable hashing so that a page s ViewState can be used from another page:

Visual Basic .NET

<%@ Page language="vb" EnableViewStateMac="false" Codebehind="RedirectNTransfer.aspx.vb" Inherits="MCSDWebAppsVB.Transfer1" %>

Visual C#

<%@ Page language="c#" EnableViewStateMac="false" Codebehind="RedirectNTransfer.aspx.cs" AutoEventWireup="false" Inherits=" MCSDWebAppsVB.Transfer2" %>

The following event procedure for an ImageButton control shows how information can be passed between forms with the Transfer method:

Visual Basic .NET

' Transfer1.aspx Private Sub imgTransfer_Click(ByVal sender As System.Object, _ ByVal e As System.Web.UI.ImageClickEventArgs) _ Handles imgTransfer.Click ' Transfer to another form, retaining ViewState. Server.Transfer("Transfer2.aspx", True) End Sub

Visual C#

// Transfer1.aspx private void ImageButton1_Click(object sender, System.Web.UI.ImageClickEventArgs e) { // Transfer to another form, retaining ViewState. Server.Transfer("Transfer2.aspx", true); }

WARNING
ASP.NET hashes ViewState information to prevent malicious users from manually changing the information passed back to the server and thus somehow corrupting data stored there. Disabling this hashing decreases the security of your Web application.

Use the Request object s Form method to retrieve the ViewState information from the source Web form. The following code displays the values of two controls from the Transfer1.aspx Web form after the preceding Transfer method executes:

Visual Basic .NET

' Transfer2.aspx Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load Dim colForm As _ System.Collections.Specialized.NameValueCollection ' Get data from source Web form. colForm = Request.Form ' Display the value from Webform1's TextBox. Response.Write("TextBox1.Text: " & _ colForm.Item("TextBox1") & "<br>") ' Display the x, y coordinates of where the click occurr ed. Response.Write("ImageButton X, Y coords: " & _ colForm.Item("imgTransfer.x") & ", " & _ colForm.Item("imgTransfer.y") & "<br>") End Sub

Visual C#

// Transfer2.aspx private void Page_Load(object sender, System.EventArgs e ) { System.Collections.Specialized.NameValueCollection c olForm; // Get data from the source Web form. colForm = Request.Form; // Display the value from Webform1's TextBox. Response.Write("TextBox1.Text: " + colForm["TextBox1"] + "<br>"); // Display the X, Y coordinated of where the click occurred. Response.Write("ImageButton X, Y coords: " + colForm["imgTransfer.x"] + ", " + colForm["imgTransfer.y"] + "<br>"); }

You can use the Server object s Transfer method to link control values across requests, as shown in Figure 4-20.

figure 4-20 the server object s transfer method

Figure 4-20. The Server object s Transfer method

NOTE
The Server object s Transfer and Execute methods work exclusively with Web forms. Trying to navigate to an HTML page using one of these methods results in a run-time error.

Using the Execute Method

Use the Server object s Execute method to process a second Web form without leaving the first Web form. This technique lets you direct the results from a Web form to a region on the current page. As with the Transfer method, Execute requires that the Web form s EnableViewStateMac attribute be set to False to disable ViewState hashing.

For example, the following code executes the Table.aspx Web form and displays it in a Literal control on the current page:

Visual Basic .NET

Private Sub butExecute_Click(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles butExecute.Click Dim swrTarget As New System.IO.StringWriter() ' Execute a Web form, store the results. Server.Execute("Table.aspx", swrTarget) ' Display the result in a Literal control. litTable.Text = "<h2>Table Results</h2>" & swrTarget.ToString End Sub

Visual C#

private void butExecute_Click(object sender, System.EventArg s e) { System.IO.StringWriter swrTarget = new System.IO.StringWriter(); // Execute a Web form, store the results. Server.Execute("Table.aspx", swrTarget); // Display the result in a literal control. litTarget.Text = "<h2>Table Results</h2>" + swrTarget.ToString(); }

The Execute method s second argument is optional. If you omit it, the result is written to the current page. The result is additive the content of both pages is displayed at the same time and server controls on both pages can respond to user events, as shown in Figure 4-21.

figure 4-21 the server object s execute method

Figure 4-21. The Server object s Execute method

When you combine Web forms using the Execute method, be aware that any postback events occurring on the second Web form will clear the first Web form. For this reason, combining Web forms is mainly useful when the second Web form does not contain controls that trigger postback events.

Displaying a Page in a New Browser Window

To start a new instance of the browser, use the client-side Window object s Open method. You can do this only as part of a client script because the new window is created on the client. However, there are ways to control the content and appearance of the new browser window from the server.

In its simplest form, the Window.Open method takes the form shown in boldface for the following Button HTML control definition:

<INPUT style="Z- INDEX: 102; LEFT: 55px; WIDTH: 81px; POSITION: absolute; TOP: 156px; H EIGHT : 24px" onclick="window.open('transfer2.aspx')" type="submit"  value="New Window">

To use a variable as the target URL, replace webform2.aspx with a data tag:

<INPUT style="Z- INDEX: 102; LEFT: 55px; WIDTH: 81px; POSITION: absolute; TOP: 156px; H EIGHT : 24px" onclick="window.open('<%# urlTarget %>')" type="submit"  value="New Window">

To update the target URL from server code, use a Public variable and data binding. The following Page_Load event procedure sets the target URL and updates it with data binding when the page loads:

Visual Basic .NET

Public urlTarget As String Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load urlTarget = "transfer2.aspx" Page.DataBind() End Sub

Visual C#

public string urlTarget; private void Page_Load(object sender, System.EventArgs e) { urlTarget = "transfer2.aspx"; Page.DataBind(); }

Because the Window.Open method takes many different arguments to control the various aspects of the new browser window, you might want to create a class to handle all the various settings. Classes allow you to encapsulate all the possible settings so that they can be used in an object-oriented manner. The following Page_Load event procedure and class definition demonstrate how to control the size, location, and URL of the new window from server-side code using a class named BrowserWindow:

Visual Basic .NET

Public urlTarget As New BrowserWindow() Private Sub Page_Load(ByVal sender As System.Object, _ ByVal e As System.EventArgs) Handles MyBase.Load With urlTarget ' Set URL for new window .URL = "execute.htm" .Top = 100 .Left = 100 .Width = 400 .Height = 400 End With ' Update HTML Button. Page.DataBind() End Sub ' Class to control new browser windows created in scripts. ' Default settings shown here are the same as browser defaul ts. Public Class BrowserWindow ' String settings: default is blank. Public URL As String = "about:blank" ' Integer settings: 0 invokes default. Public Height As Integer = 0 Public Width As Integer = 0 Public Top As Integer = 0 Public Left As Integer = 0 ' Boolean-like settings: 0 is "no" 1, is "yes" Public ChannelMode As Integer = 0 Public Directories As Integer = 1 Public FullScreen As Integer = 0 Public Location As Integer = 1 Public Resizable As Integer = 1 Public ScrollBars As Integer = 1 Public Status As Integer = 1 Public TitleBar As Integer = 1 Public ToolBar As Integer = 1 Public MenuBar As Integer = 1 End Class

Visual C#

public BrowserWindow urlTarget = new BrowserWindow(); private void Page_Load(object sender, System.EventArgs e) { urlTarget.URL = "Execute.aspx"; urlTarget.Top = 100; urlTarget.Left = 100; urlTarget.Width = 400; urlTarget.Height = 400; // Update HTML Button. Page.DataBind(); } // Class to control new browser window create in scripts. // Default settings shown here are the same as browser default s. public class BrowserWindow { // String settings: default is blank. public string URL = "about:blank"; // Integer settings: 0 invoked default. public int Height = 0; public int Width = 0; public int Top = 0; public int Left = 0; // Boolean-like settings: 0 is "no", 1 is "yes". public int ChannelMode = 0; public int Directories = 1; public int FullScreen = 0; public int Location = 1; public int Resizable = 1; public int ScrollBars = 1; public int Status = 1; public int TitleBar = 1; public int ToolBar = 1; public int MenuBar = 1; }

The HTML code for a button that uses these settings would look like the following example. (The server-supplied variable is shown in boldface.)

<INPUT style="Z- INDEX: 103; LEFT: 25px; WIDTH: 126px; POSITION: absolute; TOP: 60px; H EIGHT: 33px" type="button" value="Show New Window"  onclick="window.open('<%# urlTarget.URL %>', null, 'height=<%# urlTarget. Height %>, width=<%# urlTarget.Width %>, top=<%# urlTarget.Top %>, left=<%# urlTarget.Left %>, channelmode=<%# urlTarget.ChannelMode %>, directories=<%# urlTarget.Directories %>, fullscreen=<%# urlTarget.FullScreen %>, location=<%# urlTarget.Location %>, menubar=<%# urlTarget.MenuBar %>, resizable=<%# urlTarg et.Resizable %>, scrollbars=<%# urlTarget.ScrollBars %>, status=<%# urlTarget.Status %>, titlebar=<%# urlTarget.TitleBar %>, toolbar=<%# urlTarget.ToolBar %>')">



MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[.  .. ]0-315
MCAD(s)MCSD Self-Paced Training Kit(c) Developing Web Applications With Microsoft Visual Basic. Net and Microsoft V[. .. ]0-315
ISBN: N/A
EAN: N/A
Year: 2003
Pages: 118

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net