I know in the MVC Framework, you have the Html Class to create URLs:
Html.ActionLink("About us", "about", "home");
But what if you want to generate Urls in Webforms?
I haven't found a really good resource on the details on generating URLs with Webforms.
For example, if I'm generating routes like so:
Route r = new Route("{country}/{lang}/articles/{id}/{title}",
new ArticleRouteHandler("~/Forms/Article.aspx"));
Route r2 = new Route("{country}/{lang}/articles/",
new ArticleRouteHandler("~/Forms/ArticlesList.aspx"));
Routes.Add(r);
Routes.Add(r2);
How would i generate URLs using the Routing table data.
eg. /ca/en/articles/123/Article-Title without
Thanks for the answers. TO add to this, here is what I've done:
RouteValueDictionary rvdSiteDefaults
= new RouteValueDictionary { { "country", "ca" }, { "lang", "en" } };
Route oneArticle
= new Route("{country}/{lang}/articles/a{id}/{title}",
rvdSiteDefaults,
rvdConstrainID,
new ArticleRouteHandler("~/Articles/Details.aspx"));
Routes.Add( "Article", oneArticle);
public static string CreateUrl(Article a) {
// Note, Article comes from Database, has properties of ArticleID, Title, etc.
RouteValueDictionary parameters;
string routeName = "Article"; // Set in Global.asax
parameters
= new RouteValueDictionary {
{ "id", a.ArticleID },
{ "title", a.Title.CleanUrl() }
};
CleanUrl() returns a URL Friendly name.
VirtualPathData vpd = RouteTable.Routes.GetVirtualPath(null, routeName, parameters);
string url = vpd.VirtualPath;
return url; // eg. /ca/en/1/The-Article-Title
}
TaDa!
As you say, ASP.NET MVC offers you a set of helper methods to "reverse lookup" the RouteTable and generate a URL for you. I've not played with this much yet but as far as I can see you need to call the GetVirtualPath method on a RouteCollection (most likely RouteTable.Routes). So something like:
Dim routedurl = RouteTable.Routes.GetVirtualPath(context, rvd).VirtualPath
You need to pass the RequestContext and a RouteValueDictionary. The RouteValueDictionary contains the route parameters (so in your case something like county="UK", lang="EN-GB" etc. The tricky part is the RequestContext as this is not part of the normal HttpContext. You can push it into the HttpContext in your IRouteHandler:
requestContext.HttpContext.Items("RequestContext") = requestContext
and then restore it again in your IHttpHandler (aspx page) when required:
Dim rvd =
New RouteValueDictionary(New With {.country = "UK", .lang = "EN-GB"})
Dim routedurl =
RouteTable.Routes.GetVirtualPath(context.Items("RequestContext"), rvd).VirtualPath
Apologies for responding to a C# question in VB, it was just that the ASP.NET routing site I had to hand was in VB.NET.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With