Passing Data between Pages


Linking between static web pages allows us to group them into logical collections that allow for easy navigation. When we're dealing with dynamic pages, rather than just linking from one page to the next, we can also make use of the URL to send data between them. This is incredibly useful as it means that we can display data on one page based upon a choice that the user made previously.

Try It Out—Passing Data Between Pages

In this Try it Out, we'll edit the Discs.aspx page that is based on examples in Chapter 9, updating it so that whenever the title of a particular album is clicked on, we get taken to a second page that displays more details about it.

  1. Open up the Discs.aspx page (which is included in the code download, and is based on the examples we looked at in Chapter 9). Ensuring that you're in Design view, select the MxDataGrid on the page. As in Chapter 9, click the ellipsis within the Fields entry on the Properties pane. As we're going to link to a second page on the Title, we'll want to remove the column that's already there, and create a new HyperLinkField. To do this, select entry 1 in the Members pane, and click the Remove button. Now click the arrow next to the Add button, and select the HyperLinkField option. Select the entry that has just been created in the Members pane, and click the up arrow until it appears just below the cover image field in the list (back at position 1 in the list).

  2. The next step is to configure the field to display the Title, and to link to the DiscDetails.aspx page. To do this, update the values in the right pane, setting them as follows:

    • HeaderText – Title

    • DataNavigateURLField – DiscID

    • NavigateURLFormatString – DiscDetails.aspx?DiscID={0}

    • DataTextField – Title

    The dialog should now appear like the one shown below:

    click to expand

  3. Set the visual styles to match the other columns as follows:

    HeaderStyle

    Setting

    BackColor

    #668099

    BorderColor

    #668099

    BorderStyle

    Solid

    BorderWidth

    2px

    ItemStyle

    Setting

    BorderColor

    #668099

    BorderStyle

    Solid

    BorderWidth

    2px

    Click OK on the dialog to confirm the changes, and you should see the appearance change so that the Title column now appears in blue, showing that it is a hyperlink.

    click to expand

  4. Save the Discs.aspx file, and create a new ASP.NET Page called DiscDetails.aspx. This page will be used for displaying the details of an album that is selected from the MxDataGrid – allowing us to show the cover image on the same page as the other details. In the Design view, drag a Repeater control onto the design canvas from the Web Controls tab of the Toolbox. Now, switch to the All view of the page so that we can both retrieve the data, and output it to the screen. Update the Repeater control, so that the following ItemTemplate declaration appears within its tags; this will define how our page looks:

        <asp:Repeater  runat="server">  <ItemTemplate>  <h1>Disc Details - <%# Container.DataItem("Title")  %></h1>  <p><img src='/books/3/257/1/html/2/<%# Container.DataItem("CoverImageURL") %>'  align="center" vspace="4" /></p>  <p><b>Notes:</b> <%# Container.DataItem("Notes") %></p>  <p><b>Release Date:</b> <%# Container.DataItem("ReleaseDate") %></p>  <p><b>Label:</b> <%# Container.DataItem("Label") %></p>  </ItemTemplate>     </asp:Repeater>

  5. Next, drag a SELECT Data Method from the Code Builders tab of the Toolbox onto the page. Enter the usual details for the Connect to Database dialog, and click OK. On the next dialog, select the Disc table in the left pane, and then check the * checkbox in the right pane to choose what data is returned. After that, click the WHERE button to so that we can specify the individual record to bring back. As this dialog defaults to the DiscID field, simply click OK on this dialog. The Query Builder should now look like the following:

    click to expand

  6. Click the Next button on this and the Preview page, and you will be presented with the Caption page. Replace the MyQueryMethod text with GetDiscDetails, ensure that the DataSet radio button is selected, and click Finish.

  7. The final step is to tie the data returned from the GetDiscDetails() method to the Repeater control on our page. To do this, enter the following code above the GetDiscDetails() method:

     Public Sub Page_Load()  Repeater1.DataSource = GetDiscDetails(Request.QueryString.Item("DiscID"))  Repeater1.DataBind() End Sub 

    Save this file, switch back to the Discs.aspx file, and click the Start button on the toolbar. When the page is shown, you'll now see that the Title column contains hyperlinks. Clicking on one of these will take you to the DiscDetails.aspx page, displaying a page similar to the one below:

    click to expand

How It Works

Whenever we call an ASPX page, we can append data to the URL that appears in the address bar in the browser. This data takes the form of name-value pairs; as their name suggests, each pair has a name to identify it, and a value associated with that name. They appear on the query string prefixed by a question mark (?). If we want to have more than one item passed to a page at once, we can separate them by an ampersand (&), as in the URL below:

http://localhost:8080/DiscDetails.aspx?DiscID=1&SecondDiscID=2 

Whenever we pass data to a page in this fashion, we can retrieve it as we did on the DiscDetails.aspx page – by making a call to the Request object. This object allows us to retrieve information from the querystring (the extra information at the end of the URL after the question mark; our name-value pairs), from any forms that have been filled in, and from other data sources (such as cookies stored on the client's browser).

Note

Cookies are small text files that remember certain information relating to the user and to a specific site – we'll learn more about cookies in Chapter 15.

By specifying the following code:

Request.QueryString.Item("DiscID")

we're asking for the value of the DiscID item that was passed in on the QueryString to be retrieved. In the example above, this value (which will be a number such as 1 or 2) is then passed into the GetDiscDetails method, which returns to us all of the information about a specific Disc. The Repeater control (which is a bit like a DataGrid, but allows us to define how we want the data to be presented more simply) then displays the details of the specified Disc.

Try It Out—Encoding Data Being Passed on the Query String

One thing that you'll notice if you do some experimenting with our DiscDetails.aspx page is that if the DiscID value on the query string is altered so that it's no longer an integer, for instance a value such as x, an error message is displayed. In this Try it Out, we'll create an error page that is displayed whenever this happens, and show how data can be encoded on the query string, allowing other values to be passed around.

  1. In Web Matrix, open the DiscDetails.aspx page in Code view. Update the Page_Load routine at the top of the editor to match the code below, so that whenever an error occurs, the user is redirected to a different page:

    Public Sub Page_Load()  Try  Repeater1.DataSource = _  GetDiscDetails(Request.QueryString.Item("DiscID"))  Catch  Response.Redirect("Error.aspx?Message=" & _  Server.URLEncode("Could not retrieve results for [DiscID] specified"))  End Try  Repeater1.DataBind() End Sub

  2. Create a new ASP.NET page called Error.aspx, ensure it's in Design view, and enter the text Error at the top of the canvas. Select this text, and set it to Heading 1, then enter the following text beneath it:

    An error occurred while attempting to display the requested page

  3. Next, switch to HTML view, and update the contents of the <p> tag to match
    the following:

    <p>  An error occurred while attempting to display the requested page:   <%=Request.QueryString.Item("Message") %> </p>

  4. Finally, save both of these files, open the Discs.aspx file from within Web Matrix, and click the Start button on the toolbar. When the page is shown, click on one of the links taking you through to the DiscDetails.aspx page. Now alter the value in the address bar, so that the DiscID is set to X. When this URL is navigated to, the following screen should be displayed:

    click to expand

How It Works

When the DiscDetails.aspx page is called, it tries to make a call to GetDiscDetails(), passing through the value of DiscID as a parameter. As this function expects a number as its input, it will cause an error to be raised if we pass through an invalid value (such as X). By wrapping this line of code up in a Try ... Catch block, we ensure that if an error occurs, then the Response.Redirect() line of code is called, sending the user to the Error.aspx page, and passing through a querystring parameter called Message.

Rather than simply passing the error message straight through, the Server.URLEncode() function is called first. Looking at the text in the Address bar in Internet Explorer when the Error.aspx page is displayed, you'll see that the message has been converted to:

Could+not+retrieve+valid+results+for+the+%5bDiscID%5d+specified 

This is done because not all characters are valid in a URL. In fact, very few characters are valid – most symbols, such as the square brackets ([ and ]) in our message aren't allowed. When we pass text through to Server.URLEncode(), it replaces such characters with an encoded representation of them. Most characters get converted to a three character string, beginning with a percent (%), followed by two hexadecimal (0 9/a f) characters. Certain other values are treated differently, such as a space, which is converted to a plus (+) sign. If this encoding wasn't done, then an ampersand (&) in the middle of a string, for example, would cause a new name-value pair to be started.

Important

Whenever dynamic data is passed around on the query string, it is important to remember to call URLEncode() on it. Although datatypes such as integers are not altered when URL encoded, if the type of data is ever changed, then it could stop the system from working.

When the Error.aspx page is displayed, the line of code:

<%=Request.QueryString.Item("Message") %>

simply reads the value passed in on the query-string, and outputs it to the page for us. You'll notice that .NET takes care of decoding the text itself, re-inserting characters such as the square-brackets ([ and ]).

It should be noted that passing around server-side information via the client (either using the query-string, cookies, or any other means) is generally not considered good practice. This is because it leaves the system open to the malicious altering of these values in an attempt to gain access to parts of the system that shouldn't be accessible.




Beginning Dynamic Websites with ASP. NET Web Matrix
Beginning Dynamic Websites: with ASP.NET Web Matrix (Programmer to Programmer)
ISBN: 0764543741
EAN: 2147483647
Year: 2003
Pages: 141

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