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

前端 未结 2 1752
孤城傲影
孤城傲影 2020-12-29 02:46

Lets say you have an action method to display products in a shopping cart

 // ProductsController.cs
 public ActionMethod Index(string gender) {

      // get         


        
相关标签:
2条回答
  • 2020-12-29 03:35

    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).

    0 讨论(0)
  • 2020-12-29 03:43

    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?

    0 讨论(0)
提交回复
热议问题