views:

1193

answers:

1

I'm using Url.Encode within a view and it's replacing spaces with + so instead of:

/production/cats-the-musical I'm getting .../cats+the+musical.

I'm sure this is an easy one, but where do you go to configuring which characters are used for this?

I'll be doing this:

public static string EncodeForSEO(this UrlHelper helper, string unencodedUrl)
{
     return helper.Encode(unencodedUrl.Replace(' ', '-'));
}

Until I get a better answer from you guys.

Edit: Thanks Guffa for pointing out my hasty coding.

+3  A: 

You can't change which characters the UrlEncode method uses, the use of "+" for spaces is defined in the standards for how an URL is encoded, using "-" instead would mean that the method would change the value and not just encoding it. As the "-" character is not encoded, there would be no way to decode the string back to the original value.

In your method, there is no need to check for the character before doing the replacement. If the Replace method doesn't find anything to replace, it just returns the original string reference.

public static string EncodeForSEO(this UrlHelper helper, string unencodedUrl) {
   return helper.Encode(unencodedUrl.Replace(' ', '-'));
}
Guffa
Thanks for the code fix.It's more than just encoding, specifically it's making the url parameters more SEO friendly.On the controller side though a call to HttpUtility.Decode will decode any parts of the parameters that were encoded normally.
TreeUK
Hm... Why would "cast-the-musical" be more SEO friendly than "cats the musical"?
Guffa
Who knows, I was told it was the google-preferred way by an SEO specialist at a talk I attended. Stack Overflow seems to do the same thing too.
TreeUK