Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I create a friendly URL in ASP.NET MVC?

How do I generate friendly URLs within the ASP.NET MVC Framework? For example, we've got a URL that looks like this:

http://site/catalogue/BrowseByStyleLevel/1

The 1 is Id of the study level (Higher in this case) to browse, but I'l like to reformat the URL in the same way StackOverflow does it.

For example, these two URLs will take you to the same place:

https://stackoverflow.com/questions/119323/nested-for-loops-in-different-languages

https://stackoverflow.com/questions/119323/

EDIT: The friendly part of the url is referred to as a slug.

like image 516
Kieron Avatar asked Oct 20 '08 10:10

Kieron


1 Answers

There are two steps to solve this problem. First, create a new route or change the default route to accept an additional parameter:

routes.MapRoute(  "Default", // Route name                    "{controller}/{action}/{id}/{ignoreThisBit}",                     new { controller = "Home",                           action = "Index",                           id = "",                          ignoreThisBit = ""}  // Parameter defaults ) 

Now you can type whatever you want to at the end of your URI and the application will ignore it.

When you render the links, you need to add the "friendly" text:

<%= Html.ActionLink("Link text", "ActionName", "ControllerName",                     new { id = 1234, ignoreThisBit="friendly-text-here" }); 
like image 198
Craig Stuntz Avatar answered Oct 08 '22 23:10

Craig Stuntz