Performing Page Navigation (Scenario 1)


Page navigation among multiple pages is a common scenario in virtually all web applications. The following sample demonstrates how to use the <asp:hyperlink runat="server"> control to navigate to another page (passing custom query string parameters along the way). One of the properties of the HyperLink class is NavigateUrl, which gets or sets the URL to link to when the HyperLink control is clicked. The sample then demonstrates how to get access to these query string parameters from the target page. Also, this example shows how NOT to separate the HTML script from C# code, though it is not recommended because the source code will be difficult to read.

In order to do that, the following options are selected:
   Project ⇒ Add New Item...


Controls5_cs.aspx

Web
<%@ Page Language="C#" AutoEventWireup="true"
  CodeBehind="Controls5_cs.aspx.cs"
  Inherits="WebApplication11.Controls5_cs" %>

<script language="C#" runat="server">
 protected void Page_Load( object sender, EventArgs e ) {
  Random random = new Random( DateTime.Now.Millisecond );
  int randomNum = random.Next( 3 );
  switch( randomNum ) {
   case 0:
    Name.Text = "Scott";
    break;
   case 1:
    Name.Text = "Fred";
    break;
   case 2:
    Name.Text = "Adam";
    break;
  }
  AnchorLink.NavigateUrl = "Controls_NavigationTarget_cs.aspx?name=" +
   Server.HtmlEncode( Name.Text );
 }
</script>

<html xmlns="http://www.w3.org/1999/xhtml"> 
 <body>
  <form runat=server>
   <h3><font face="Verdana"> 
    Performing Page Navigation (Scenario 1)
   </font></h3>
   This sample demonstrates how to generate an HTML 
   Anchor tag that will cause the client to navigate
   to a new page when he/she clicks it within the browser.
   <hr />
   <asp:hyperlink id="AnchorLink" font-size="24" runat="server">
    Hi <asp:label id="Name" runat="server" /> please click this link!
   </asp:hyperlink>
  </form>
 </body>
</html>