As I mentioned we are learning the new enhancements in ASP.NET 4 and ASP.NET 4 Web Forms from scratch at the Sarasota Web Developer Group. At the first meeting we talked about many of the new enhancement in ASP.NET 4 Web Forms, including the new enhancements in ASP.NET 4 Web Forms Routing.
GetRouteUrl
In my last post I neglected to mention the Control.GetRouteUrl Method in System.Web.UI as a way to get routes from the route name and various route parameters. Using the following route from the previous post:
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
);
}
}
One can get the route for a particular contact inside a Page_Load Event, for example, by calling GetRouteUrl on the Page as follows:
protected void Page_Load(object sender, EventArgs e)
{
var route = GetRouteUrl("Contact_Details", new { id = 1 });
}
The value of route in this case will be “/Contact/Details/1″.
GetRouteUrl when DataBinding in Grid
The GetRouteUrl Method is particularly useful in a Grid when you want to display a list of contacts with a link to the details of each. Shown below is just a snippet of the Grid source code where I am using GetRouteUrl with the proper Route Name and Parameters within the NavigateUrl Property of the HyperLink:
<asp:TemplateField>
<ItemTemplate>
<asp:HyperLink
ID="HyperLink1"
runat="server"
NavigateUrl='<%# GetRouteUrl("Contact_Details", new {id = Eval("Id") }) %>'
Text='<%# Eval("Id") %>'>
</asp:HyperLink>
</ItemTemplate>
</asp:TemplateField>
Conclusion
I’ll be posting about other topics presented at the group. If you live in the area, please come out and attend the second meeting focusing on ASP.NET MVC, DynamicData, Castle ActiveRecord, and more. I’ll also be presenting What’s New in ASP.NET 4 at the Orlando Code Camp.