Lets say you have an action method to display products in a shopping cart
// ProductsController.cs
public ActionMethod Index(string gender) {
// get
My solution was this :
An HtmlExtension helper method :
public static string RouteUrl(this UrlHelper urlHelper, string routeName, object routeValues, bool inheritRouteParams)
{
if (inheritRouteParams)
{
// call standard method
return urlHelper.RouteUrl(routeName, routeValues);
}
else
{
// replace urlhelper with a new one that has no inherited route data
urlHelper = new UrlHelper(new RequestContext(urlHelper.RequestContext.HttpContext, new RouteData()));
return urlHelper.RouteUrl(routeName, routeValues);
}
}
I can now do :
Url.RouteUrl('testimonials-route', new { }, false)
and know for sure it will always behave the same way no matter what the context.
The way it works is to take the existing UrlHelper
and create a new one with blank 'RouteData'. This means there is nothing to inherit from (even a null value).
Maybe I'm missing something here, but why not set it up like this:
In your global asax, create two routes:
routes.MapRoute(
"testimonial-mf",
"Testimonials/{gender}",
new { controller = "Testimonials", action = "Index" }
);
routes.MapRoute(
"testimonial-neutral",
"Testimonials/Neutral",
new { controller = "Testimonials", action = "Index", gender="Neutral" }
);
Then, use Url.Action instead of Url.RouteUrl:
<%= Url.Action("Testimonials", "Index") %>
<%= Url.Action("Testimonials", "Index", new { gender = "Male" }) %>
<%= Url.Action("Testimonials", "Index", new { gender = "Female" }) %>
Which, on my machine resolves to the following urls:
/Testimonials/Neutral
/Testimonials/Male
/Testimonials/Female
I'm not sure if this is an acceptable solution, but it's an alternative, no?