views:

415

answers:

1

To get the URL's I wanted i created a simple Link Creator helper for my search results. But it wont let me use server urlencode in it and some of the details passed are French/Czech/Swedish words commas and apostrophes;

Is there a quick function that will strip all this garbage out before hand?

A: 

Create custom HTML helper for this. Generate HTML markup using TagBuilder and use UrlEncode where you want. For example:

public static string SearchActionLink(this HtmlHelper html, string linkText, string actionName, object routeValues)
{
    var innerHtml = html.ViewContext.HttpContext.Server.UrlEncode("....");

    TagBuilder tagBuilder = new TagBuilder("a") {
        InnerHtml = innerHtml;
    };

    var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
    var url = urlHelper.Action(actionName, routeValues);
    tagBuilder.MergeAttribute("href", url);

    return tagBuilder.ToString(TagRenderMode.Normal);
}

UPDATED:

Something like this?:

public static string SearchActionLink(this HtmlHelper html, string linkText, System.Web.Routing.RouteValueDictionary routeValues)
{
    var ref = html.ViewContext.HttpContext.Server.UrlEncode(routeValues["ref"]);
    routeValues["ref"] = "_REF_";

    TagBuilder tagBuilder = new TagBuilder("a") { InnerHtml = linkText; };

    var urlHelper = new UrlHelper(html.ViewContext.RequestContext);
    var url = urlHelper.RouteUrl(routeValues).Replace("_REF_", ref);

    tagBuilder.MergeAttribute("href", url);

    return tagBuilder.ToString(TagRenderMode.Normal);
}
eu-ge-ne
Ta, technically though I wouldn't want to url encode the label <a>LABEL</a> and InnerHtml = innerHtml shouldn't have the semi-colon.The only problem with this is that it produces links /routevalues/action/
Chris M
You can use any `Url.Action` or `Url.RouteUrl` you want or maybe I misunderstand you question :) Where is the problem with `UrlEncode` exactly?
eu-ge-ne
My URL's are like this: /companies/city/town/ref <ref is the ID.Some of the Cities/Towns contain dodgy characters (For a uri) like ,'
Chris M
Chris M
I've updated my answer
eu-ge-ne
perfect :o)Thanks
Chris M
You're welcome.
eu-ge-ne
Instead of: html.ViewContext.HttpContext.Server.UrlEncode couldn't you use: HttpUtility.UrlEncode?
Adam Kahtava