How to dynamically create urls/links like: www.restaurant.com/restaurant/restaurant-name-without-some-characters-like-space-coma-etc/132
what are the keywords i can use to google some articles on this topic? (how to genererate and handle this kind of urls inside asp.net mvc)
There are some questions: How to generate links? (store slugs in db?) Redirect or not if slug isn't canonical?
edit: apparently they are called slugs
I just asked a relevant question today on SO regarding to generating slug, aka/ slugify a title.
When fetch a URL with slug, you can either create an action that takes both
ID
(and other required arguments) andslug
in and simply ignore the slug.Or more elegant, Use map route to ignore trialing string behind your URL and map to
Foobar(int id)
.You have to use something as follows.
And a simple extension method:
I've always stored slugs in the database alongside whatever entity would be referenced by them. So for a blog post, you would have a "slug" field in the "posts" table.
To handle it in ASP.Net MVC is easy - you just use a regular route that would capture the slug in a parameter (possibly even just using {id}), and then your controller would look up the slug in the database, load the entity, and display it as normal.
Although you can use a simple RegEx to replace spaces and whatnot to generate your slugs, in reality this breaks down pretty quickly. You need to consider all kinds of characters that may appear in your titles. Michael Kaplan's blog has been linked to heavily for this exact purpose; he's shared a function that will strip diacritical marks from strings.
So, your "generate slug" algorithm should generally take the form of:
One way to do this is the following on your string
Now you can pass the
cleanString
(for titles,names etc) into the ActoinLink/Url.Action parameters and it will work great.The pattern was taken from http://snipplr.com/view/18414/string-to-clean-url-generator/
I'm not 100% on the Regex pattern, if some Regex hero can chime in and offer a better one that would be great. From testing the Regex, it doesn't match spaces, but this shouldn't be a problem because the first line replaces all spaces with hyphens.
Update:
To use this code, you need to setup your routes to accept extra parameters.
We'll use a blog article title as an example.
In your ASP.NET MVC views, you can then do the following:
In the previous example, I use
SanitizeTitle
as an HTML helper.