09.03
The ASP.NET Routing module is responsible for mapping incoming browser requests to controller actions. When you create a new ASP.NET MVC application, the application is configured with some standard routes in the Global.ascx file. The route table is created during the Application Start event of the Global.ascx file.
Line 2: tells MVC to ignore any requests to .axd files and not route them to an MVC controller.
Line 3-11: adds a default route which maps to a URL which matches the format:
/Details/Index/3
The default route maps this URL to the following parameters:
controller = Details
Action = Index
ID =3
Line 8-9: sets some defaults for the controller and action, so if we type a url such as http://my-site.co.uk/ it would automatically map to the Home controller’s Index action.
Line 10: specifies that the id field is optional.
The example below shows the corresponding Index method of the DetailsController this method is invoked by the URL /Details/Index/3 and /Details/Index
Default routes are all well and good but what if we want something not default? Well out of the box the routing in MVC is clever enough to route URLs with query string parameters on, so for example:
| URL | Maps to |
|---|---|
| /Search/ | Index |
| /Search/Results?query=iphone | Results |
The first URL /Search/ we already understand how this maps from the previous examples but the second URL /Search/Results?query=iphoneis more interesting. This values can be read from the query string just like they could be in normal ASP.NET, whilst there is nothing wrong with this URL we can make it better. What if you wanted to use the following URLs?
| URL | Maps to |
|---|---|
| /Search/ | Index |
| /Search/IPhone | Results |
| /Search/IPhone/2 | Results |
We can enable these URLs by adding some additional routes into the Global.ascx file
You must add this new route above the default otherwise the default route will be mapped and you will end up in the wrong place. The route is not that different to the default one, instead of using {controller} to specify that the URL specifies the controller we want instead the URL starts with /Search/ but instead goes to the Search Controllers Results action. Line 10: indicates that the page is optional so in the case no page is specified it is defaulted to 1 otherwise the value passed.
The Action method for this route would look like the following:
