tags:

views:

184

answers:

1

I have the following link defined in a page that will be built based on the route defined in the web.config

<%= Html.RouteLink(product.DisplayName, "ShopProductNames", new {Id = product.Id, ProductName = product.DisplayName.Replace(' ', '-') }) %>

I need to URL encode the DisplayName in the URL of that link, however, when I add encoding in the following way:

<%= Html.RouteLink(product.DisplayName, "ShopProductNames", new {Id = product.Id, ProductName = Url.Encode(product.DisplayName.Replace(' ', '-')) }) %>

It double encodes my DisplayName (in the URL), and I get an error in IIS.

My DisplayName property is not being encoded before it's passed to the page. Also, RouteLink does not appear to be Url encoding for the rendered link by default as it's not picking up spaces or ampersands when the page is rendered.

Anyone know what I'm doing wrong?

UPDATE: I'm actually referring to the URL generated by RouteLink, not the link text itself

UPDATE 2: here is the route I'm using

routes.MapRoute(
            "ShopProductNames",
            "Shop/{productName}/p/{id}/{*nameInfo}",
            new
            {
                controller = "Product",
                action = "Detail"
            }
            );
A: 

Look at HtmlHelper.cs file, line 140:

internal static string GenerateUrl(string routeName, string actionName, string controllerName, RouteValueDictionary routeValues, RouteCollection routeCollection, RequestContext requestContext, bool includeImplicitMvcValues)
{
    RouteValueDictionary mergedRouteValues = RouteValuesHelpers.MergeRouteValues(actionName, controllerName, requestContext.RouteData.Values, routeValues, includeImplicitMvcValues);

    VirtualPathData vpd = routeCollection.GetVirtualPath(requestContext, routeName, mergedRouteValues);
    if (vpd == null) {
        return null;
    }

    string modifiedUrl = PathHelpers.GenerateClientUrl(requestContext.HttpContext, vpd.VirtualPath);
    return modifiedUrl;
}

Url is created by routeCollection.GetVirtualPath() method (System.Web.Routing.dll). Using Reflector you'll see that it uses Uri.EscapeDataString() internally (System.Web.Routing.ParsedRoute.Bind method)

eu-ge-ne
Ok, if that's the case, then something isn't right, when I leave off the Url.Encode(ProductName) it should take spaces and ampersands and encode them, but that is certainly not happening.
Ryan Eastabrook