Reading Routing Information in a Web Forms Page

In the code of the Web Forms physical page, you can access the information that routing has extracted from the URL (or other information that another object has added to the RouteData object) by using two new properties: HttpRequest.RequestContext and Page.RouteData. (Page.RouteData wraps HttpRequest.RequestContext.RouteData.) The following example shows how to use Page.RouteData.

protected void Page_Load(object sender, EventArgs e)

{

string searchterm = Page.RouteData.Values["searchterm"] as string;

label1.Text = searchterm;

}

The code extracts the value that was passed for the searchterm parameter, as defined in the example route earlier. Consider the following request URL:

http://localhost/search/scott/

When this request is made, the word "scott" would be rendered in the search.aspx page.

Accessing Routing Information in Markup

The method described in the previous section shows how to get route data in code in a Web Forms page. You can also use expressions in markup that give you access to the same information. Expression builders have been described as a "hidden gem of ASP.NET" (see the entry Express Yourself With Custom Expression Builders on Phil Haack's blog). It is unfortunate that they are not better known, because expression builders are a powerful and elegant way to work with declarative code.

ASP.NET 4 includes two new expression builders for Web Forms routing. The following example shows how to use them.

<asp:HyperLink ID="HyperLink1" runat="server"

NavigateUrl="<%$RouteUrl:SearchTerm=scott%>">Search for Scott</asp:HyperLink>

In the example, the RouteUrl expression is used to define a URL that is based on a route parameter. This saves you from having to hard-code the complete URL into the markup, and lets you change the URL structure later without requiring any change to this link.

Based on the route defined earlier, this markup generates the following URL:

http://localhost/search/scott

ASP.NET automatically works out the correct route (that is, it generates the correct URL) based on the input parameters. You can also include a route name in the expression, which lets you specify a route to use.

The following example shows how to use the RouteValue expression.

<asp:Label ID="Label1" runat="server" Text="<%$RouteValue:SearchTerm%>" />

When the page that contains this control runs, the value "scott" is displayed in the label.

The RouteValue expression makes it very simple to use route data in markup, and it avoids having to work with the more complex Page.RouteData["x"] syntax in markup.

Posted in: asp.net | Tags: asp.net asp.net 4.0 webform web application routing web form