This tutorial is brought to you by NetroStar, a web design company.
One of the most important features of ASP.NET MVC is Routing. It is used to call appropriate controller method based on requests from web browser. Basically it maps URL address to a concrete action from controller. In this tutorial I will explain you how does MVC Routing work. If you're not familiar with ASP.NET MVC yet check out
How to create your first application in ASP.NET MVC 3.0
Route table
The default route table is created along with a new project in "Global.asax"
file. You can see how it works in the following code:
The route table is created just after application has started when the
Application_Start() method is called. In the beginning there is only one route
created named "Default" with the following default parameters:
controller="Home", action="Index", id="".
As you probably remember URL for MVC Controller looks like this:
/[name of the Controller]/[name of the method]?[parameters]
Our default route is corresponding to the following URL address:
http://localhost:xxxxx/Home/Index. So method Index() is called from
HomeController class.
Now let's imagine that you entered following URL to address bar:
http://localhost:xxxxx/Countries/ShowCountries, our route table maps this
address to the following code: CountriesController.ShowCountries(). So
ShowCountries() method from CountriesController class is invoked.
Adding a new route to the route table
Now we'll create a new route, however note that usually default route table
is enough for most MVC applications. But sometimes you might find it useful to
add a new route to your application. Let's take a look at this piece of code:
Global.asax file:
CountriesController.cs file:
As you can see CountriesController just calls an appropriate view.
Now if you want to invoke ShowCountries() method from CountriesController
class you just have to specify controller class in URL and the default value for
action will be ShowCountries. So URL address:
http://localhost:xxxxx/Countries/ShowCountries and
http://localhost:xxxxx/Countries will both result in calling ShowCountries()
method.
Remember that the order of routes in route table matters. Imagine that we'll
switch entries in Global.asax file like this:
What would happen now? If you enter address like:
http://localhost:xxxxx/Countries in address bar of your browser an error would
be raised. That's caused because of the fact that this address would be matched
to the first entry in route table with the following parameters: controller =
"Countries" and action="Index" (default action that is chosen if no action was
specified in URL). However in CountriesController file there is no method such
as Index and that's why exception is raised.
To sum up MVC Routing can be a very useful tool and although usually it's not
necessary to use it it's good to know what is going on under the hood of your
application.
This tutorial was brought to you by NetroStar, a Miami-based global seo company.