Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add page title in url in asp.net mvc? (url generation)

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

like image 503
Ante Avatar asked Feb 01 '10 05:02

Ante


People also ask

How to make Header in ASP net?

The AddHeader method adds a new HTTP header and a value to the HTTP response. Note: Once a header has been added, it cannot be removed.

What is URL rewriting in MVC?

URL rewriting is the process of intercepting an incoming Web request and redirecting the request to a different resource. When performing URL rewriting, typically the URL being requested is checked and, based on its value, the request is redirected to a different URL.


2 Answers

You have to use something as follows.

Routes.MapRoute(
    "Post",
    "posts/{id}/{*title}",
    new { controller = "Posts", action = "view" }
);

And a simple extension method:

public static class UrlExtensions
{

    public static string ResolveSubjectForUrl(this HtmlHelper source, string subject)
    {
        return Regex.Replace(Regex.Replace(subject, "[^\\w]", "-"), "[-]{2,}", "-");
    }

}
like image 125
Mehdi Golchin Avatar answered Sep 29 '22 21:09

Mehdi Golchin


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:

  1. Trim the string of leading/trailing whitespace
  2. Strip diacritical marks using Michael Kaplan's function or equivalent
  3. Lowercase the string for canonicalization
  4. Replace all the non-word characters with dashes
like image 41
womp Avatar answered Sep 29 '22 20:09

womp