Using Routing with Web Forms

Although the main focus of this book is on ASP.NET MVC, Routing is now a core feature of ASP.NET, so you can use it with Web Forms as well. This section first looks at the easy case, ASP.NET 4, because it includes full support for Routing with Web Forms.

In ASP.NET 4, you can add a reference to System.Web.Routing to your Global.asax and declare a Web Forms route in almost the exact same format as an ASP.NET MVC application:

download
void Application_Start(object sender, EventArgs e)
{
       RegisterRoutes(RouteTable.Routes);
}

private void RegisterRoutes(RouteCollection routes)
{
       routes.MapPageRoute(
             "product-search",
             "albums/search/{term}",
             "∼/AlbumSearch.aspx");
}

Code snippet 9-21.txt

The only real difference from an MVC route is the last parameter, in which you direct the route to a Web Forms page. You can then use Page.RouteData to access the route parameter values, like this:

protected void Page_Load(object sender, EventArgs e)
{
    string term = RouteData.Values["term"] as string;

    Label1.Text = "Search Results for: " + Server.HtmlEncode(term);
    ListView1.DataSource = GetSearchResults(term);
    ListView1.DataBind();
}

Code snippet 9-22.txt

You can use Route values in your markup as well, using the new <asp:RouteParameter> object to bind a segment value to a database query or command. For instance, using the preceding route, if you browsed to /albums/search/beck, you can query by the passed route value using the following SQL command:

<asp:SqlDataSource id="SqlDataSource1" runat="server"  
    ConnectionString="<%$ ConnectionStrings:Northwind %>"
    SelectCommand="SELECT * FROM Albums WHERE Name LIKE @searchterm + ‘%’">
  <SelectParameters>
    <asp:RouteParameter name="searchterm" RouteKey="term"  />
  </SelectParameters>
</asp:SqlDataSource>

Code snippet 9-23.txt

You can also use the RouteValueExpressionBuilder to write out a route parameter value a little more elegantly than just writing out Page.RouteValue[“key”]. If you want to write out the search term in a label, you can do the following:

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

Code snippet 9-24.txt

You can generate outgoing URLs for using the Page.GetRouteUrl() in code-behind logic method:

string url = Page.GetRouteUrl(
    "product-search", 
    new { term = "chai" });

Code snippet 9-25.txt

The corresponding RouteUrlExpressionBuilder allows you to construct an outgoing URL using routing:

<asp:HyperLink ID="HyperLink1" 
       runat="server" 
       NavigateUrl="<%$RouteUrl:SearchTerm=Chai%>">
             Search for Chai
</asp:HyperLink>

Code snippet 9-26.txt

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.147.62.94