How to prevent Url.RouteUrl(…) from inheriting route values from the current request

元气小坏坏 提交于 2019-11-30 04:20:19

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?

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!