Could someone explain how routes are associated with controllers in MVC 2? Currently, I have a controller in /Controllers/HomeController.cs and a view /Home/Index.aspx.
My route registration method looks like this:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.IgnoreRoute("{resource}.aspx/{*pathInfo}");
routes.MapRoute(
"Default",
// Route name
"{controller}/{action}/{id}",
// URL with parameters
new { controller = "Home", action = "Index", id = "" }
// Parameter defaults
);
}
If I request the URL: http://localhost/Home/Index, then the request is correctly handled by HomeController.Index().
However, for the life of me, I can’t figure out how the url /Home/Index gets pointed to HomeController. The view aspx doesn’t, as far as I can tell, reference HomeController, HomeController doesn’t reference the view, and the route table doesn’t explicitly mention HomeController. How is this magically happening? Surely I’m missing something obvious.
then
The default views engine that comes with ASP.NET MVC works on the following conventions:
You have a folder structure like this:
When a request comes in, and matches a route defined in the RegisterRoutes method (see things like URL routing for more on that), then the matching controller is called:
In the default route, you are also specifying a default controller (without the "Controller" suffix) – the routing engine will automatically add
Controlleronto the controller name for you – and a default action.In your controller, you call the simple method:
The default view engine then looks for an aspx file called Index (the same as the action) in a folder called "Home" (the same as the controller) in the "Views" folder (convention).
If it doesn’t find one in there, it will also look for an index page in the Shared folder.
From the ASP.NET MVC Nerd Dinner sample chapter
Edit to add:
Some example routes I’ve set up, that explicitly set the controller are:
Here I’m explicitly stating that I’m using the Albums controller, and the PhotoDetails action on that, and passing in the various ids, etc to the that action.