View Single Post
Old April 10th, 2010, 02:06 PM
Anto Anto is offline
Registered User
Join Date: Apr 2010
Posts: 2
Thanks: 0
Thanked 0 Times in 0 Posts
Smile One possible solution

After disassembling and trying to understand Scott Mitchell's example of url routing in 3.5 with web forms, I've come up with a very simple sample in, which is my favourite language. Basically, in the class file containing the routehandler which has been registered in Global.asax, the parameter is first grabbed from the route data values of the RequestContext:
   Dim categoryName As String =   requestContext.RouteData.Values("CategoryName")
Then it's added to the items in the current httpcontext:

 Dim catName As String = categoryName
 System.Web.HttpContext.Current.Items("Category") = catName
                Return CType(BuildManager.CreateInstanceFromVirtualPath("~/CategoryProducts.aspx", GetType(Page)), Page)
In the page that needs to grab the parameter from the url in order to display the right item, just grab the value of the item in the items collection of the current httpContext object, normally you'd have used a Request.QueryString to retrieve this value:

 Dim category As String = HttpContext.Current.Items("Category")
The Url is dynamically reconstructed by using a Helpers class with a method such as this:

 Public Shared Function FormatCategoryUrl(ByVal categoryName As String) As String
        Dim strVirtualPathData As VirtualPathData
        Dim params As RouteValueDictionary

        params = New RouteValueDictionary(New With {.categoryName = categoryName})

        strVirtualPathData = RouteTable.Routes.GetVirtualPath(Nothing, "View Category", params)
        Return strVirtualPathData.VirtualPath

    End Function
For example, in the hyperlink that leads to the products by category page, its NavigateUrl property will be something like:

 <asp:HyperLink ID="hlGoToCategory" runat="server" 
            NavigateUrl='<%# Helpers.FormatCategoryUrl(Eval("CategoryName").ToString()) %>' 
            Text='<%#Eval("CategoryName") %>'></asp:HyperLink>
I understand that things might get a bit more complicated by adding authentication and authorization for example, but I just needed an extremely simple application so that I could grasp the basic workings of the url routing mechanism. Also, I'm aware that the all thing has been simplified in .Net 4.