Only Bolivian Here
Only Bolivian Here

Reputation: 36743

How to add a 'text slug' to a page url in MVC3?

Check out what StackOverflow does:

http://stackoverflow.com/questions/8933768/c-sharp-boolean-outside-method-wont-read

The URL works without the final decorator, that is mainly used for SEO purposes.

I want something like this on my ASP.Net MVC3 application.

Assuming on the Article table I have a field Slug nvarchar(1024) not null, how do I push this out of the routing engine so it appears when someone visits the link?

I want the ID to be visible and the link to work even without the slug at the end. In case I ever change the slug in the database, any links would still work as the ID would be the only link to the article.

A clear, short example would be phenomenal.

Upvotes: 3

Views: 1659

Answers (3)

Nathan Taylor
Nathan Taylor

Reputation: 24606

The best way to do this is to have the second part of the url, the slug, be an irrelevant field in terms of how the lookup is done. Your route definition would be something like this:

routes.MapRoute(
    "article"
    "articles/{id}/{slug}",
    new { controller = "Article", action = "Index", slug = "" }
);

And the matching action:

public ActionResult Index(int id, string slug) {
    var article = _repository.GetById<Article>(id);

    ......

    return View();
}

If you're concerned about people requesting an invalid slug with a valid ID (and the impact this can have on SEO), then your controller action might have an additional operation which validates the slug against the article and does a 301 redirect to the desired URL whenever an incorrect slug is provided. This is what StackOverflow does, by the way. If you modify the title part of a question URL you will see that the site redirects you.

Upvotes: 7

STO
STO

Reputation: 10648

at first declare a routing "slug" parameter then pass it via route values when defining action link or action url.

Upvotes: -1

Anthony Shaw
Anthony Shaw

Reputation: 8166

routes.MapRoute("Slugged", "{controller}/{action}/{id}/{slug}", new { controller = "Home", action = "Index", id = UrlParameter.Optional });'

Then, for the action that handles your call, accept both an id and slug parameter.

I would then verify that the slug provided matches the slug from the actual record in the databsae, if it doesn't, 301 redirect to the correct id and slug (the reason I say this, is so you don't get marked down in SEO if people figure out that your slugs can be changed and link to you in many different ways)

Upvotes: 2

Related Questions