Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Control.GetRouteUrl from a class in App_Code

I'm using routing in asp.net web forms 4.0 with some success. In my pages I am using Page.GetRouteURL to generate routes like this.

<a href = '<%=GetRouteUrl("MyRoute", new {MyFirstRouteValue = "ABC", MySecondRouteValue=123}) #>' >Link Text</a>

This works perfectly well, but I have found that there are times when I need to have this functionality in a class in app_code. I could just manually build the route with String.Format, but that is kind of sloppy since it would duplicate the code in Global.asax that defines the routes.

Of course, there is no Page object in a class in App_Code, so I can't just call GetRouteUrl. Looking up in the docs on msdn I see somethingthat looks helpful.

This method is provided for coding convenience. It is equivalent to calling the RouteCollection.GetVirtualPath(RequestContext, String, RouteValueDictionary) method.

So I followed the docs to this page which states that System.Web.Routing.GetVirtualPath() requires a System.Web.Routing.RequestContext object. I know about the HttpContext object, but I can't figure out what a RequestContext is. Anybody had any luck with this?

like image 601
John Hoge Avatar asked May 09 '11 20:05

John Hoge


1 Answers

RequestContext is available as a property to HttpRequest object, so you can refer it as HttpContext.Current.Request.RequestContext. For example,

public string GetRouteUrl(string routeName, object routeParameters)
{
   var dict = new RouteValueDictionary(routeParameters);
    var data = RouteTable.Routes.GetVirtualPath(HttpContext.Current.Request.RequestContext, routeName, dict );
    if (data != null)
    {
        return data.VirtualPath;
    }
    return null;
}
like image 115
VinayC Avatar answered Oct 14 '22 03:10

VinayC