Remove Ambiguty of Controller Names in MVC Application

In this article I am sharing my thoughts of how to create a routing system in a MVC application and the terminology being used.

Here we go


This mechanism examines an incoming URL and then decides which controller and action the request needs to be sent.

Open your Visual Studio, select "File" -> "New" -> "Project..." and select "ASP.NET MVC3 Web Application", as in the following:


Specify whatever name for your first application you desire and click "Ok".

A new window will appear, from that window I seelcted Intranet application whilst many options are there. Another interesting fact is that there is a dropdown named "View Engine"; I selected Razor that is more specific to MVC 3 and MVC 4 and kept the checkbox "create a new unit test" unchecked.


Click on the "Ok" button.

The following screen depicts the default one that comes after clicking on the "OK" button having multiple folders.


We need to make some amendments to this to understand how routing works. The Application_Start method is responsible for registering the RegisterRoutes method. This Application_Start method is called by the ASP.NET platform when the application is started first.

To explore more on routing in MVC, have a look into the link:

Let's see what happens when we run our application for the first time with default routing settings.


Which fulfills this route system?


Whenever we hit the URL http://localhost:60346/, first it jumps to the given class and asks for the action method named "verify" as is depicted in the following image:


Let's look into the image below to understand how to correlate the namespaces of the .cs file and the routing path defined in global.asax. If you notice the red encircled box, both point to the same namespace, MVCSample.Controllers, in other words whenever such an URL is hit by the user having the same pattern defined in the route it will hit this class first.

If I remove the namespace parameter from the route then it throws the following error:


This error occurs because we've defined two controllers with the same name in a solution That causes confusion that should be descibed here.


To overcome this issue we must use a controller name with a complete namespace.

Here we define the route to resolve such issues, as the following image shows:


After defining the route in the application it runs perfectly:


If you hit the next URL http://localhost:60346/Views/Register/RegisterAction then it jumps into the different controller in the MVCSample.Register namespace, as in:


And gives you the result accordingly as below:


So using the namespace parameter in routing makes it much more convenient for the end-user to solve such issues.

Hope this will help you and many other geeks. The sample application has been attached as a reference.

Enjoy MVC and Routing.

Up Next
    Ebook Download
    View all
    View all