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

前端 未结 2 1766
孤城傲影
孤城傲影 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).

提交回复
热议问题