Web Forms Routing in ASP.NET 4

At our first Sarasota Web Developer Group meeting we discussed several of the new enhancements in ASP.NET 4 Web Forms. One of my favorite enhancements is the new routing features which are very similar to the ones I have enjoyed so much in ASP.NET MVC.

 

Register Routes

This is old hat for those using ASP.NET MVC. Just register your routes at application startup. Rather than your endpoint being a controller, however, you associate a physical page as the handler of the request.

 

public class Global : System.Web.HttpApplication
{
    void Application_Start(object sender, EventArgs e)
    {
        RegisterRoutes(RouteTable.Routes);
    }

    void RegisterRoutes(RouteCollection routes)
    {
        routes.MapPageRoute(
            "Contact_Details",                  // Route Name
            "Contacts/Details/{id}",          // Url and Parameters
            "~/Contacts/Details.aspx"     // Page Handling Request
            );
    }
}

 

In this case we are telling the routing engine 3 things:

  • Name of the Route: Contact_Details
  • The Route: Contacts/Details/{id}
  • The Physical Page Handling the Request: Details.aspx

 

Notice the id parameter ( route value ) which will be the id of the contact to display in the details page.

 

Expression Builders for Creating HyperLinks, etc.

With ASP.NET MVC we have strongly-typed View Helpers to help generate links. With ASP.NET 4 Web Forms you utilize Expression Builders to create links such as:

 

<asp:HyperLink
    NavigateUrl="<%$RouteUrl:RouteName=Contact_Details, id=1 %>"
    runat="server">John Doe
</asp:HyperLink>

<asp:HyperLink
    NavigateUrl="<%$RouteUrl:id=1%>"
    runat="server">John Doe
</asp:HyperLink>

 

We can explicitly specify the name of the route or let the routing engine figure out the correct route based on the parameters.

 

Getting RouteData from the Page

You can access the RouteData from the Page by accessing the Page.RouteData Property, which is just a convenient access point to RequestContext.RouteData. Here are a couple of ways to get the id from the route to display the proper contact given its id:

 

public partial class Details : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        var id = Page.RouteData.GetRequiredString("id");

        var id2 = Page.RouteData.Values["id"];
    }
}

 

RouteParameter for use with DataSources

If you are displaying the contact in a DetailsView, for example, you can use the new RouteParameter with your DataSource to get values from the route as such:

 

<asp:ObjectDataSource ID="ObjectDataSource1" runat="server"
    SelectMethod="FindById" TypeName="Contact">
    <SelectParameters>
        <asp:RouteParameter Name="id" RouteKey="id" Type="Int32" />
    </SelectParameters>
</asp:ObjectDataSource>

 

Binding your DetailsView to the ObjectDataSource will now cause the contact to be displayed appropriately.

 

Response.RedirectToRoute and RedirectToRoutePermanent

A lot has been mentioned about using Response.RedirectPermanent for SEO, but even cooler is Response.RedirectToRoute and Response.RedirectToRoutePermanent for working with the new routing engine. Below I am specifying the route name and passing in any route values where necessary when redirecting:

 

Response.RedirectToRoute("Contact_Details", new { id = 1 });

Response.RedirectToRoutePermanent("Contact_Details", new { id = 1 });

 

Conclusion

Lots of really neat things in ASP.NET 4 and ASP.NET 4 Web Forms. I am going to continue to post a few more we discussed during the first meeting.

For those interested, the second meeting of the Sarasota Web Developer Group will discuss a number of interesting topics: Leveraging ASP.NET MVC – Web Forms – DynamicData – Castle ActiveRecord.

 

David Hayden

 

This entry was posted in Uncategorized. Bookmark the permalink. Follow any comments here with the RSS feed for this post.

One Response to Web Forms Routing in ASP.NET 4

  1. Richard says:

    Is it possible to combine the RouteUrl expression builder with data binding? For example, you show a static hyperlink for contact ID 1, but what if you need to show a data-bound list of contacts with links to view their details?

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>