Joydip Kanjilal
Contributor

Best practices in ASP.Net MVC

opinion
Jun 26, 20154 mins
Software Development

Take advantage of the recommended best practices and tips to build applications using ASP.Net MVC that can scale and are responsive, fast, easier to test and maintain

This is another post on the series of articles on best practices. In this one, I’ll present the best practices that should be followed while working with ASP.Net MVC framework.

What is the MVC design pattern all about?

First off, let’s take a quick tour of the basics. What is the MVC (Model View Controller) design pattern all about? Why is it needed, anyway? Well, the user interface often contains a lot of cluttered code primarily because of the complicated logic it needs to handle. The presentation patterns are designed primarily with one objective in mind: reducing the complex code in the presentation layer and making the code in the user interface clean and manageable.

The MVC framework helps you build applications that are easier to test and maintain. It comprises of three major components, namely, the Model (represents the application’s data and business logic), the View (this represents the presentation layer) and the Controller (this typically represents the business logic of your application). The MVC design pattern enables you to isolate the concerns and makes your application’s code easier to test and maintain.

The Controller

You should delete the demo code files — the AccountController.cs file as you wouldn’t need it anyway. The AccountController is created by default and is not needed — just delete it! You should also reduce the coupling between your controllers and other dependencies like data access component, exception and logging blocks, etc. You controllers should be as slim as possible and contain much less code. Ideally, you should just delegate the control flow to some business logic component inside your controller class. The controller in an ASP.Net MVC application should be isolated from the data access layer — the controller is responsible to render the appropriate view at runtime based on certain action.

Bundling and minifying the script and CSS files

You should group resources your application needs to use like CSS files into one downloadable resource. This process is also known as bundling. You should also minify the scripts and CSS files you would use to remove the unnecessary characters, comments and white space characters.

The following code snippet illustrates how you can create a bundle object for the CSS your application needs to use.

public static void RegisterBundles(

                       BundleCollection bundles)

{

   bundles.Add(new StyleBundle(“~/Content/Styles”)

       .Include(“~/Content/Styles/bootstrap.css”,

                “~/Content/Styles/IDG.css”));

}

The following code shows how you can bundle the script files you need to use in your application.

  .Include(

     “~/Content/Scripts/IDG-1.0.0.js”,

     “~/Content/Scripts/knockout-3.0.0.js”)

);

Note how the ScriptBundle class is used to bundle the script content. Similarly, the StyleBundle class (as shown in the earlier example) is used to bundle the css content we discussed earlier.

You should also turn off the checking of routes unless it is absolutely needed so as to eliminate the unnecessary processing overheads involved.

Views

You should use strongly-typed views wherever possible — I would recommend sending POCOs to the views in your ASP.Net MVC application. You should do all processing in your controllers and not the views — the views should be lean and should not contain any business logic code. You should use minimal amount of TagHelpers in your Html helpers and you should remember to use HtmlHelpers only when you need conditional decisions to be taken on the data through the views. If there is a need of a conditional statement in your view, you should move it to an HtmlHelper. The HtmlHelpers should never contain code that invokes the data access layer, i.e., you should refrain from writing data access logic inside the HtmlHelpers. You should not put JavaScript code in your view – seperate them into distinct script files.

Cache your data

To improve the performance and responsiveness of your application, you can take advantage of caching. Caching is a technique that enables you to store relatively stale data in the memory so as to reduce the network bandwidth consumption. The following code snippet shows how you can use caching in your controllers.

public class IDGController : Controller

{

    [OutputCache(Duration=3600,

VaryByParam=”none”)]

    public ActionResult Index()

    {

    }

}

You should also cache frequently accessed pages that contain shared data and don’t need to be authorized. The following code snippet illustrates how you can do this.

[OutputCache(Duration = 3600)]

public ActionResult Index()

{

  return View(“Index”, myDataObject);

}

The MVC design pattern helps enforcement of a clean separation of concerns amongst the models, views and controllers within your application. This helps your code to be easily tested and maintained. I have discussed some important points that you can consider when working with ASP.Net MVC to build applications that are high performant, easier to test, maintain and scale. I’ll discuss more on ASP.Net MVC in the forthcoming posts here. So, stay tuned!

Joydip Kanjilal
Contributor

Joydip Kanjilal is a Microsoft Most Valuable Professional (MVP) in ASP.NET, as well as a speaker and the author of several books and articles. He received the prestigious MVP award for 2007, 2008, 2009, 2010, 2011, and 2012.

He has more than 20 years of experience in IT, with more than 16 years in Microsoft .Net and related technologies. He has been selected as MSDN Featured Developer of the Fortnight (MSDN) and as Community Credit Winner several times.

He is the author of eight books and more than 500 articles. Many of his articles have been featured at Microsoft’s Official Site on ASP.Net.

He was a speaker at the Spark IT 2010 event and at the Dr. Dobb’s Conference 2014 in Bangalore. He has also worked as a judge for the Jolt Awards at Dr. Dobb's Journal. He is a regular speaker at the SSWUG Virtual Conference, which is held twice each year.

More from this author