I have been converting a ASP.Net Webforms application to MVC. The application is used to pull up information pertaining to servers and instances on our corporate network. MVC is a perfect fit for this application because people will often look up information by URL hacking and the pretty URLs used by MVC make it easier for users to find data.
When using MVC, the controller is the generally the second part of the URL, followed by the action and the Id. If I followed this pattern, then my URL for viewing the details of an instance would look like this:
http://SomeUrl/Instances/Details/InstanceName
| Controller | Instances |
| Action | Details |
| ID | InstanceName |
I thought this pattern was a little bit too verbose and I wanted users to be able to use a URL like this instead.
http://SomeUrl/Instances/InstanceName
In order to use my own custom URL mapping I need to create a custom route. This is accomplished by registering a new route in the Global.asax file.
routes.MapRoute( "Instances",
"Instances/{InstanceName}",
new { controller = "Instances", action = "Details" });
It is important that you register this route before the other auto-generated routes. Otherwise it will not work.
So this code basically says that if you have a URL that follows the pattern "Instances/<InstanceName>" then invoke the Details method in the Instances controller. In the Instances controller you now will have to change the signature of the Details method to accept a new parameter which is the Instance Name. It should look like this:
public ActionResult Details(string InstanceName) {}
Note: The parameter name matches the name used in the MapRoute call above.
MVC is very flexible and once you understand how the basics of it work you can customize it to do just about anything. There are a few paradigm shifts that you will need to get used to, such as not having code-behinds for your views (they can be added manually if required). After using MVC for only one week I already prefer it over the Webforms approach. The first reason is because I feel like it allows me to have a better separation between my data and presentation layer. Secondly, the directory structure created by starting a new MVC application really helps you organize your code. And thirdly, the pretty URLs really make it easier for users to navigate around your website:
URL Before: http://SomeURL/Instances.aspx?instanceName=SQLSERVER01
URL After: http://SomeURL/Instances/SQLSERVER01
Suggested Reading: