[RESOLVED]Remove characters from friendly url's

I’m using RouteTable.Routes.MapWebPageRoute() for routing but the urls are showing special charactors. How can I remove special characters in the URL and just add a dash to separate each word?

Right now the urls are showing:

http://localhost:51758/products/computers/desk%20top

I’m trying to get:

http://localhost:51758/products/computers/desk-top

%20 means you have a space in between desk and top.

Why can’t you make the string desktop or desk-top ?

If you have a route 

RouteTable.Routes.MapWebPageRoute("/products/{cat1}/{cat2}", "~/products.cshtml", new {cat1=something1, cat2=something2 });

then you can just use replace " " with "-" i.e. something2.replace(" ","-")

then you might need to do same .replace("-"," ") to get the original value back to be able to display it or query a database.

The problem here is that if you would have a category with "-" in the name, e.g. "cd-rom" then this logic my be not the best and in this case it would be better to keep name and route separately in the database e.g.

Name        Route
-------------------------
Desk Top    desk-top
Laptop      laptop
CD-ROM      cd
Sale %%% sale

So that you could use customized rows for any name

You can use the algorithm that Stackoverflow uses to generate a slug, which takes care of special characters: http://stackoverflow.com/questions/25259/how-does-stack-overflow-generate-its-seo-friendly-urls.

Note: the code makes use of a custom method called RemapInternationalCharToAscii, which replaces all non-ASCII characters with their ASCII equivalent for the URL. It isn’t featured in that post, but can be found here: http://meta.stackexchange.com/questions/7435/non-us-ascii-characters-dropped-from-full-profile-url/7696#7696

Leave a Reply