Simplest MVC Controller routing

I’ve ported a number of websites from old static (or nearly so) pages over to more recent .net mvc technology, just for the benefit of being able to use templates and manage/automate a few things better than having to edit individual html files. Yes, Im a fan of Orchard CMS but some of these sites just arent worth the effort of trying to port to Orchard, or at least not for now. Creating a custom theme just for one site just wouldnt be worth the effort.

When doing these kinds of sites, you could use a single “Home” controller for all your pages, and add a controller method for each page. With 20+ pages, you would add a method and a single View for each page you port over… kinda burdensome for a simple site.

So, what I’ll often do is just simplify the Index() method on the controller so it can show the requested view, whatever it may be. You can implement this as follows (yes I’ll add code formatting to this eventually…)-

in HomeController, we add a parameter to the Index() method so we can pass in the name of the view.

public ActionResult Index(string view) {
   return View(view);

In Global.asax, we change the default routing to use:

   “{view}/{id}”, // URL with parameters
   new { controller = “Home”, action = “Index”, view=”Index”, id = UrlParameter.Optional } // Parameter defaults

Now, the default controller “Home” calls Index by default, and passes in the first parameter as the view name. We simply load the view with that name and display it. Note that this route can mess you up fast if you try to do anything fancier, but it’s a good way to simplify a really simple site that is basically a collection of views… perfect for porting over our old pages from and old static site.

Leave a Reply

Your email address will not be published. Required fields are marked *