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 ...

Get Professional ASP.NET MVC 3 now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.