Home » ASP.Net MVC Routing

ASP.Net MVC Routing

by Online Tutorials Library

ASP.NET MVC Routing

In MVC, routing is a process of mapping the browser request to the controller action and return response back. Each MVC application has default routing for the default HomeController. We can set custom routing for newly created controller.

The RouteConfig.cs file is used to set routing for the application. Initially it contains the following code.

// RouteConfig.cs

According to this setup file, Index action of Home controller will be treated as default. First time, when application runs it produces the following output.

ASP Routing 1

If we look at the address bar, it contains only localhost:52174. There is no controller and action is specified because MVC router maps the controller from the RouteConfig.cs.

If we explicitly enter controller and action names in the address bar, it will redirect to the same action. The localhost:52174/Home/Index will produce the same output to the browser.

ASP Routing 2

Now, let’s create a new controller and configure it to the route file. Right click on the Controller folder and select add then controller. It will pop up a window. select an empty controller as we did in screen shot.

ASP Routing 3

This controller has some source code, override this with the following code.

// StudentsController.cs

To configure this controller in route file, we have made some changes in RouteConfig.cs file. Code is given below.

// RouteConfig.cs

This application produce the same output for localhost:52174 and localhost:52174/Students/Index

Because route module of MVC framework maps the browser URL to the RouteConfig file of the project.

Output:

ASP Routing 4

This is same as above even we have entered controller and action names explicitly.

ASP Routing 5

You may also like