spacer

Webref WebRef   Sitemap · Experts · Tools · Services · Newsletters · About i.com

home / programming / asp_net4 / 1 To page 1To page 2To page 3To page 4current pageTo page 6
[previous][next]

Technology Consultant Manager (IL)
Next Step Systems
US-IL-Chicago

Justtechjobs.com Post A Job | Post A Resume
Developer News
OpenOffice 3.2 Lands Amid Critical Changes
Red Hat, IBM Firmly in KVM Virtualization Camp
Red Hat Talks Up Open Source Cloud Plans


Build Your Own ASP.NET Website Using C# and VB.NET. Pt. 4.

Handling Page Navigation

Links from page to page are what drives the Web. Without linking, the Web would be little more than a simple page-based information source. Links enable us to move effortlessly from page to page with a single click; they bridge the gaps between related ideas, regardless of the boundaries imposed by geography and politics. This section focuses on page navigability using:

Suppose for a minute that you have created a Website that allows your users to choose from a selection of items on one page. You could call this page viewcatalog.aspx. Imagine that you have a second page, called viewcart.aspx. Once users select an item from viewcatalog.aspx, you’d probably want to link them directly to viewcart.aspx so that they can keep track of their orders. To achieve this, we clearly must pass the information from the viewcatalog.aspx page over to the viewcart.aspx page.

Using The HyperLink Control

The HyperLink control creates a simple HTML hyperlink on a page. Once it’s clicked, the user is redirected to the page specified by the NavigateUrl property. For instance:

<asp:HyperLink id="hlAddToCart" NavigateUrl="viewcart.aspx" 
    runat="server" Text="View Cart" />

Here, the NavigateUrl property specifies that this link leads to the page called viewcart.aspx. Figure 4.3 shows how the HyperLink control is rendered in the browser.

Figure 4.3. The HyperLink control renders similar to the anchor tag in the browser.

The HyperLink control renders similar to the anchor tag in the browser.

However, once we’ve arrived at the new page, it has no way of accessing the information from the first page. If we need to provide the user some continuity of information, we need something else.

Navigation Objects And Their Methods

The previous example rendered a simple control similar to the HTML anchor tag. Once the link is followed, however, we have no record of the previous page or any data it contained (the Web is a stateless technology).

If we wish to pass information from one page to the next, we can use one of the three methods listed below to create the link between the pages:

Response.Redirect()

Navigates to a second page from code. This is equivalent to using the HyperLink control, but allows us to set parameters on the query string dynamically.

Server.Transfer()

Ends the current Web Form and begins executing a new Web Form. This method only works when the user is navigating to a new Web Form page (.aspx).

Server.Execute()

Begins executing a new Web Form while displaying the current Web Form. The contents of both forms are combined in the response sent to the browser. Again, this method only works when the user is navigating to a Web Forms page (.aspx).

The easiest and quickest way to redirect your users from the viewcatalog.aspx page to the viewcart.aspx page would be using Reponse.Redirect():

Sub linkClk(s As Object, e As EventArgs)
  Response.Redirect("viewcart.aspx")
End Sub
void linkClk(Object s, EventArgs e) {
  Response.Redirect("viewcart.aspx");
}

You could then use the LinkButton control to call this subroutine as follows:

<asp:LinkButton id="lbAddToCart" Text="Add To Cart" 
    OnClick="linkClk" runat="server"/>

This time, when you click the LinkButton control, the Click event is raised, the subroutine is called, and Response.Redirect() is called with the name of the page we want to link to as a parameter. In this way, we’re redirecting to the new page directly from the code, rather than by using a particular tag. This enables us to pass information to the new page in the query string.

The query string is a list of variables and their respective values that we can append to a page’s URL, allowing us to retrieve those variables and values from that page’s code.

As an illustration, imagine you have a drop-down list that contains the following product information:

<p><asp:DropDownList id="ddlProducts" runat="server">
  <asp:ListItem Text="Pants" />
  <asp:ListItem Text="Shirt" />
  <asp:ListItem Text="Hat" />
  <asp:ListItem Text="Socks" />
</asp:DropDownList></p>

<p><asp:LinkButton id="lbAddToCart" Text="Add To Cart" 
    OnClick="linkClk" runat="server" /></p>

The code you use to handle link clicks will need to find the item selected in the drop-down list and append it to the query string of the URL to which the user is to be redirected, as follows:

Sub linkClk(s As Object, e As EventArgs)
  Dim strQueryStr As String = "?Product=" & _
    Server.UrlEncode(ddlProducts.SelectedItem.Text)
  Response.Redirect("viewcart.aspx" & strQueryStr)
End Sub
void linkClk(Object s, EventArgs e) {
  string strQueryStr = "?Product=" +
    Server.UrlEncode(ddlProducts.SelectedItem.Text);
  Response.Redirect("viewcart.aspx" + strQueryStr);
}

Note the use of the Server.UrlEncode() method, which converts characters not allowed in query string values (e.g. &) to URL-safe character codes (e.g. %26) that the browser will understand. You should always use this method when adding arbitrary values to query strings.

When a user selects an item from the drop-down list and clicks the LinkButton control, the viewcart.aspx page is opened with the selected product appended as a parameter of the query string. This is illustrated in Figure 4.4.

Figure 4.4. Append the selected item to the query string.

Append the selected item to the query string.

Now that you’ve passed the product to the viewcart.aspx page, you have to grab it from the query string in the new page. We get hold of variables from the query string by accessing the Request.QueryString collection, like so:

Sub Page_Load()
  lblResult.Text = Request.QueryString("Product")
End Sub
void Page_Load() {
  lblResult.Text = Request.QueryString["Product"];
}

Here, we simply display the value of the Product query string parameter, as we see in Figure 4.5.

Figure 4.5. Set the text property of the label control within a Page_Load event handler to accept the new parameter value.

Set the text property of the label control within a Page_Load event handler to accept the new parameter value.

Now, when you select a product and add it to the cart, the result is displayed in the redirected page on a label with an id of lblResult. Now sure, a real product catalog and shopping cart has a lot more to it, but in this section we’ve uncovered an important building block.

Postback

Postback can be confusing to newcomers because, while most ASP.NET developers know what it is, they can’t seem to explain it clearly. The topics we’ve covered so far, like subroutines, functions, and events, are not new to most Web developers. HTML, in combination with client-side JavaScript, has been doing all that for years. ASP.NET is different to this model, though, because it is a server-side, not client-side, technology—events that occur on a page are handled by code running on the server. For this to work, ASP.NET uses the mechanism of postback.

When an event is triggered, for instance, a button is clicked, or an item in a grid is selected, the page is submitted back to the server for processing, along with information about the event and any preexisting data on the page (via view state). We say the page “posts back” to the server. This is a powerful concept to grasp because it is postback that lets us run code on the server rather than on the client’s browser, and it is postback that lets our server code know which items within a drop-down list were selected, or what information a user typed into a text box.

But what would happen if you had multiple DropDownList controls that were populated with database data? Users could interact with those DropDownList controls and, in turn, we could set certain options within the page based on what they selected from the drop-down menus. Although this seems like a common task, with traditional ASP it incurred considerable overhead. The problem is that while the data that’s bound to the drop-down menu from the database never changes, every time the user selects an item from the drop-down menu and a postback has to be done, the database must be accessed again to rebuild the contents of each drop-down list on the page. However, this is not a problem in ASP.NET.

In ASP.NET we can check for postback with the IsPostBack property, and thus avoid performing any time consuming tasks unnecessarily. IsPostBack is a page-level property—meaning that it’s a property of the page itself—and we’d most commonly use it in the Page_Load() event handler to execute code only when the page is first loaded. Consider the following example:

Example 4.4. PostBack.aspx

<html>
<head>
<script runat="server" language="VB">
Sub Page_Load(s As Object, e As EventArgs) 
  lblMessage1.Text = Now()
  If Not IsPostBack Then
    lblMessage2.Text = Now()
  End If
End Sub
</script>
</head>

<body>
<form runat="server">
  <p>Not Checking for postback:<br />
    <asp:Label id="lblMessage1" runat="server" /></p>
  <p>Checking for postback:<br />
    <asp:Label id="lblMessage2" runat="server" /></p>
  <p><asp:Button id="btnClick" Text="Click Me" runat="server" />
  </p>
</form>
</body>
</html>

Example 4.5. PostBack.aspx

<html>
<head>
<script runat="server" language="C#">
void Page_Load(Object s, EventArgs e) {
  lblMessage1.Text = Convert.ToString(DateTime.Now);
  if (!IsPostBack) {
    lblMessage2.Text = Convert.ToString(DateTime.Now);
  }
}
</script>
</head>

<body>
<form runat="server">
  <p>Not Checking for postback:<br />
    <asp:Label id="lblMessage1" runat="server" /></p>
  <p>Checking for postback:<br />
    <asp:Label id="lblMessage2" runat="server" /></p>
  <p><asp:Button id="btnClick" Text="Click Me" runat="server" />
  </p>
</form>
</body>
</html>

The result will look similar to Figure 4.6.

Figure 4.6. The IsPostBack property checks to make sure the user isn’t resubmitting the page.

The IsPostBack property checks to make sure the user isn’t resubmitting the page.

In this example, the IsPostBack check means that the second label doesn’t refresh when the Button control is clicked. Similarly, we could use IsPostBack within the Page_Load() subroutine to set up database-driven drop-down menus just once within each user’s session, making the online experience smoother, and making our application more scalable. Don’t worry if postback seems a bit confusing now—we’ll use it more in upcoming chapters, so if it doesn’t yet, it should make sense after a few more practical examples.

home / programming / asp_net4 / 1 To page 1To page 2To page 3To page 4current pageTo page 6
[previous][next]


The Network for Technology Professionals

Search:

About Internet.com

Legal Notices, Licensing, Permissions, Privacy Policy.
Advertise | Newsletters | E-mail Offers

webref The latest from WebReference.com Browse >
Search Engine Optimization: Selecting and Embedding Keywords · Are Google's Language Translation Web Services Ready for Prime Time? · Installing and Using Meeplace, the Business Review CMS
Sitemap · Experts · Tools · Services · Email a Colleague · Contact FREE Newsletters 
 The latest from internet.com
IBM DB2 10 for z/OS: Justifying the Upgrade · Living La Vida Colo: Choosing the Right Colocation Facility · FTC Concerns over Social Media Privacy Linger

Created: March 27, 2003
Revised: July 12, 2004

URL: http://webreference.com/programming/asp_net4/1