Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding Redundant Information to a MVC Route

As you come to this question you'll notice the title of the question is in the address bar and the link you clicked on to get here. I am not sure the exact terminology so found it difficult to search for but how can I do something similar? That is, How can I add data to the address bar which is purely for show/search engines.

Thanks

like image 406
Damien Avatar asked Jul 17 '09 10:07

Damien


2 Answers

Taking the example of a Stack Overflow question like this one the URL is:

so.com/questions/1142480/adding-redundant-information-to-a-mvc-route

However, the functional part of the URL is:

so.com/questions/1142480

The way this is achieved is by defining a route like this:

routes.MapRoute(
    "questions",
    "questions/{id}/{title}",
    new { controller = "Questions", action = "Details", title = "" });

You then create a link to it like this:

<%= Html.RouteLink("Adding Redundant Information to a MVC Route", 
        new 
        { 
            controller = "Questions", 
            id = 1142480, 
            title = "adding-redundant-information-to-a-mvc-route" 
        }
    )
%>

I would imagine the URL title is created from the actual title by lower casing, replacing spaces with dashes and a couple of other things (escaping/striping bad characters).

So long as your SEO route appears before any other matching route the SEO route will be used.

For complete clarity the controller would actually be like this:

public class QuestionsController : Controller
{
    public ActionResult Details(int id)
    {
        // stuff for display - notice title is not used
    }
}
like image 156
Garry Shutler Avatar answered Sep 30 '22 20:09

Garry Shutler


One thing you should realize is that the text at the end of this URL is actually a dummy. For example, this URL:

  • Adding Redundant Information to a MVC Route

will open this question cleanly. Similarly, a title other than your question:

  • Adding Redundant Information to a MVC Route

will ALSO open this question without errors.

You can easily use some title-parsing algorithm to generate an "SEO friendly" URL for you complete with the title, and add it at the end of the question number. Your MVC route will just ignore the last part.

like image 34
Jon Limjap Avatar answered Sep 30 '22 20:09

Jon Limjap