Page.GetRoutUrl in a static method
Some background on what I'm doing
I usually like to have my pages return the u开发者_如何学编程rl needed to access it. So i will normally have a method like so
public partial class ProductDetails : Page
{
public static string GetUrl(Guid productId)
{
return "fully qualified url";
}
}
on my other pages/controls that need to access this page i'll simply set the link as
hl.NavigateUrl = ProductDetails.GetUrl(id);
I'm toying around with the new UrlRouting stuff in 4.0 and ran into something I'm not sure will work. I'm trying to use the Page.GetRouteUrl in my static method, and obviously it's blowing up due to Page not being static.
Does anyone know if it's possible replicate what i'm doing with GetRouteUrl?
thx
You can do something like:
var url = ((Page)HttpContext.Current.Handler).GetRouteUrl(id);
Note: If you called this method from another page, you may not get the desired result if it's relative-specific in some way...but it's as good as you can get with static I believe.
I got GetRouteUrl to work using Nicks suggestion above.
I also found an alternative way to do it w/o using the GetRouteUrl. You are basically generating it manually using GetVirtualPath
public static string GetUrl(int productId)
{
var parameters = new RouteValueDictionary { { "productId", productId } };
var vpd = RouteTable.Routes.GetVirtualPath(null, "product-details", parameters);
return vpd.VirtualPath;
}
精彩评论