MVC Controller Best Practices

MVC Controller Best Practices

Here are a few basic best practice guidelines to keep in mind when writing your controllers using the MVC pattern with ASP.NET MVC.
  • Keep controllers “skinny, keep action methods small
    • Your controller actions should be kept as small as possible, with business logic living in your models.  “Fat Model, Skinny Controller” is the motto. Here is a weird reminder of that  😯
  • Use an Inversion of Control (IoC) container (i.e. Spring, Ninject, etc) to manage dependencies
    • IoC is a must. It will make testing your code SOOOO much easier. You want to minimize any new object instantiations and instead defer to your IoC container to handle that for you. It’s just one less thing to worry about in your app. Looking for an IoC container? .NET Guru Scott Hanselman has put together a list of some IoC containers that he has used.
  • Do not rely on magic strings, but instead rely on strongly-typed views 
    • Magic strings are bad. It doesn’t mean they should never ever be used, but it’s a lot of times tough to argue for them when you have the compile time safety of a strongly typed view. Magic strings don’t lend themselves as much to easy refactoring.
    • Stay away from  ( ViewData[“myKey]) or ( ViewBag.MyKey=”myKey”) in your controllers as much as possible. Although I do believe TempData has it’s place, that is another topic most likely…
  • Use your action verbs (Post/Get)

These are just a few quick best practices to help you write better controllers with ASP.NET MVC. Any other helpful controller best practices I am missing?

By | 2012-07-24T22:23:42+00:00 July 24th, 2012|Categories: ASP.NET, MVC|0 Comments

About the Author:

Leave A Comment