Setting the index as the default route for the controller

I have url

which I want to turn into

It could also be something like http://www.roadkillwiki.org/Page/my-url-with-spaces - the parameter is a string. Setting up the route I tried:

routes.MapRoute( "ControllerDefault", "{controller}/{id}", new { controller = "Page", action = "Index", id = UrlParameter.Optional } ); 

However, this interferes with the standard "id" route with which MVC projects are associated. Is there any way to achieve this?

+7
source share
2 answers

You do not need to lose the default route. The key to avoiding your routes getting in the way is to arrange them so that more specific rules precede less specific ones. For example:

 // Your specialized route routes.MapRoute( "Page", "Page/{slug}", new { controller = "Page", action = "Index" } ); // Default MVC route (fallback) routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); 

Then your PageController will look like this:

 using System.Web.Mvc; public class PageController : Controller { public string Index(string slug) { // find page by slug } } 

However, I would strongly advise you to do this:

 // Your specialized route routes.MapRoute( "Page", "Page/{id}/{slug}", new { controller = "Page", action = "Index", slug = UrlParameter.Optional } ); // MVC default route (fallback) routes.MapRoute( "Default", // Route name "{controller}/{action}/{id}", // URL with parameters new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults ); 

And your PageController:

 using System.Web.Mvc; public class PageController : Controller { public string Index(int id) { // find page by ID } } 

By including the page id at the beginning of your URL (e.g. StackOverflow) or at the end, you can simply ignore the pool and instead get your pages by id. This will save a ton of headaches if your users change the page name. I survived it, and it is painful; you basically need to record all the names that your pages had in the past, so your visitors / search engines do not get 404 every time the page is renamed.

Hope this helps.

+15
source

If you do not need the default route that comes with the project template, you can configure it as follows:

 routes.MapRoute( "ControllerDefault", "{controller}/{pagename}", new { controller = "Page", action = "Index" } ); 

And than in your controller you will have an action:

  public ActionResult Index(string pagename) { //do something } 
+1
source

All Articles