I’ve managed to get my Home controller working by only using the action name to access it, but as soon as I add another controller and try do the same thing by adding another route declaration the same at my Home route declaration, all the routes default to the Home controller.
routes.MapRoute("HomeTest", "{action}/{id}", new { controller = "Home", action = "TestHome", id = UrlParameter.Optional });
routes.MapRoute("TestTest", "{action}/{id}", new { controller = "Test", action = "Test", id = UrlParameter.Optional });
public class HomeController : Controller
{
public ActionResult TestHome(int? id)
{
return View();
}
}
public class TestController : Controller
{
public ActionResult Test(int? id)
{
return View();
}
}
Is there any way I can access both controllers without including the controller name in the url?
I also have the default route included if that makes any difference. It’s under these two routes.
Routes in MVC are compared in the order you add them. For your code sample, this means that all requests will be compared to the “HomeTest” route first, so any matches will follow that route. The “TestTest” route has the exact same format, which means that it will never be used because any matches will have already used the “HomeTest” route. If you want to get to get to a controller’s actions without using the controller name, there must be something in the route to tell it which controller to use. This doesn’t have to be the actual controller name – you can do this:
where the keywords basically act as aliases to hide your controller names. You can even go one step further and mask your action names as well, which can let you use multiple controllers under one URL root:
Doing something like this can let you give your users a much tidier URL structure to help them navigate your site and understand where links will take them (potentially also handy for bookmarking) but it does mean you have to manually define your URLs, which is more work.