Top 10 ASP.NET MVC Best Practices

Take advantage of the powerful features in ASP.NET MVC to build robust applications with ease.

This article takes a look at the 10 best practices that can be followed for best and efficient use of ASP.NET MVC Framework 4.

Pre-requisites

As of this writing, ASP.NET MVC 4 has been released. To execute the code examples illustrated in this article, you should have the following installed in your system:

  • ASP.NET MVC 4
  • Visual Studio 2010

What is the ASP.NET MVC Framework?

The ASP.NET MVC Framework is based on the popular and time tested Model View Controller (MVC) Design Pattern. It facilitates designing and implementing applications where you can have a cleaner separation of concerns, better code organization, seamless testability, easy extensibility, scalability and code reuse.

The Official ASP.NET Website states: "The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view, and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating MVC-based Web applications. The ASP.NET MVC framework is a lightweight, highly testable presentation framework that (as with Web Forms-based applications) is integrated with existing ASP.NET features, such as master pages and membership-based authentication. The MVC framework is defined in the System.Web.Mvc namespace and is a fundamental, supported part of the System.Web namespace." Reference: http://www.asp.net/mvc/tutorials/overview/asp-net-mvc-overview

If you want to upgrade your ASP.NET MVC 3 applications to ASP.NET 4, here’s what you would need to do:

Locate the following text in the application's web.config file:

  • System.Web.Mvc, Version=3.0.0.0
  • System.Web.WebPages, Version=1.0.0.0
  • System.Web.Helpers, Version=1.0.0.0
  • System.Web.WebPages.Razor, Version=1.0.0.0

Now, replace the above with the following text:

  • System.Web.Mvc, Version=4.0.0.0
  • System.Web.WebPages, Version=2.0.0.0
  • System.Web.Helpers, Version=2.0.0.0,
  • System.Web.WebPages.Razor, Version=2.0.0.0,

Delete all references to the following assemblies in your application:

  • System.Web.Mvc (v3.0.0.0)
  • System.Web.WebPages (v1.0.0.0)
  • System.Web.Razor (v1.0.0.0)
  • System.Web.WebPages.Deployment (v1.0.0.0)
  • System.Web.WebPages.Razor (v1.0.0.0)

Add references to the following assemblies:

  • System.Web.Mvc (v4.0.0.0)
  • System.Web.WebPages (v2.0.0.0)
  • System.Web.Razor (v2.0.0.0)
  • System.Web.WebPages.Deployment (v2.0.0.0)
  • System.Web.WebPages.Razor (v2.0.0.0)

Top 10 Best Practices

In this section we will discuss 10 best practices and tips we should keep in mind when working with ASP.NET MVC applications.

Tip 1: Disable Request Validation

Request Validation is a feature that prevents potentially dangerous content from being submitted. This feature is enabled by default. However, at times you might need your application to post HTML markup tags to the server. You would then need this feature to be disabled. Here is how you can do it:

[ValidateInput(false)]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create([Bind(Exclude="Id")]Employee empObj)
{

}

Tip 2: Cache Your Data

You can improve your application's performance to a considerable extent by caching relatively stale data. That way the network bandwidth between the client and the server is also reduced. It is great if you can also cache the rendered action of web pages that are relatively stale, i.e., don’t change much over time.

public class HomeController : Controller
{
    [OutputCache(Duration=3600,
VaryByParam="none")]
    public ActionResult Index()
    {
     
    }
}

Tip 3: Isolate Data Access Logic From the Controller

The Controller in an ASP.NET MVC application should never have the Data Access logic. The Controller in an ASP.NET MVC application is meant to render the appropriate view based on some user interface action. You should make use of Repository Pattern to isolate Data Access Logic from the Controller – you might need dependency injection to inject the appropriate Repository to your controller at runtime.

Tip 4: Using a Master View Model

We frequently use Master Pages in ASP.NET applications – the same Master Page would be extended by the Content Pages throughout the application to give a similarity as far as look and feel and functionality is concerned. How do we do that in an ASP.NET MVC application? Well, we need a MasterViewModel similar to what is shown in the code snippet below:

public class ViewModelBase
{
    public ViewModelBase()
    {

    }
//Other methods and properties
}

Tip 5: Use Strongly Typed Models

A strongly typed view is a view that defines its data model as a CLR type instead of a weakly typed dictionary that may contain potentially anything. To create a strongly typed view, check the "Create a strongly-typed view" checkbox while you are creating the view. If you plan to create a strongly typed view manually later, ensure that your view "Inherits" System.Web.Mvc.<Your Namespace>.<YourClass>

Tip 6: Use Data Annotations for Validation

You can make use of the System.ComponentModel.DataAnnotations assembly to validate your server - side code by simply decorating your model with the necessary attributes. Here is an example:

public class Employee
{
    [Required(ErrorMessage="Employee Name Cannot be Blank")]
    public string Name { get; set; }

    // ...
}

Tip 7: Take Advantage of Model Binding

Consider the following code snippet:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Create()
{
    Employee employee = new Employee();
    employee.Name = Request.Form["Name"];
    
    // ...
    
    return View();
}

You can make use of model binder to save you from having to use the Request and HttpContext properties - just use FormsCollection instead. Here is an example:

public ActionResult Create(FormCollection values)
{
    Employee employee = new Employee();
    employee.Name = values["Name"];      
            
    // ...
            
    return View();
}

Tip 8: Cache Pages that Contain Shared Data or are Public and don't Require Authorization

You should not cache pages that need authorization in ASP.NET MVC. You should not cache pages that contain private data or need authorization. Caching pages in ASP.NET MVC is simple - just specify the OutputCache directive as shown in the code snippet below:

[OutputCache(Duration = 60)]
public ActionResult Index()
{
  return View("Index", somedata);
}

Tip 9: Use Extension Methods

You can make use of Extension Methods to simplifies use of LINQ queries that boost application performance too. This can dramatically reduce the amount of code that you would need to otherwise write when writing your LINQ queries, make your LINQ queries manageable and also improve the application's performance.

Tip 10: Take Advantage of Model Binding

You can take advantage of Microsoft Velocity - a distributed caching engine to boost the application performance of your ASP.NET MVC applications. You can learn more on Velocity from this link: http://blogs.msdn.com/b/velocity/

Suggested Readings

http://www.asp.net/mvc

Summary

Scott Guthrie states in his blog: “One of the benefits of using an MVC methodology is that it helps enforce a clean separation of concerns between the models, views and controllers within an application. Maintaining a clean separation of concerns makes the testing of applications much easier, since the contract between different application components are more clearly defined and articulated.” Reference: http://weblogs.asp.net/scottgu/archive/2007/10/14/aspnet-mvc-framework.aspx

In this article we discussed the top 10 best practices that we should follow while using ASP.NET MVC Framework 4 applications. Happy reading!



Related Articles

Comments

  • Very Good Article

    Posted by Manoj Kalla on 08/12/2014 03:55am

    Dear, This is very article. Nice. .

    Reply
  • tip #1

    Posted by hm on 07/05/2014 06:46am

    Very weird to see "Disable Request Validation" as the first tip. You should definately not encourage this. There are always workaround and IF you for whatever reason would ever need to disable this you should disable it on a page-basis and not for the entire web application.

    Reply
  • N.A

    Posted by Vijay Patel on 04/21/2014 11:13pm

    Sorry but i am not agree with your Tip 1. if you will make it disable Chances of XS attack will be high.

    Reply
  • come involve that

    Posted by rnqathPN on 07/23/2013 03:11am

    than http://www.mystbarts.co.uk/?p=louboutin-uk ghd hair dryer http://www.cswl.co.uk/?p=christian-louboutin-outlet-uk louboutin uk http://www.farmingtonfresh.net/?p=coach-purses true religion jeans http://streetscooterchrome.com/raybanoutlet/?p=ray-ban http://electrochem-inc.com/cheapmichaelkors/?p=cheap-michael-kors-bags ray ban 3025

    Reply
  • enHqq UqF Itlp

    Posted by PSvSrCrrpJ on 06/21/2013 07:30pm

    Continued is generic vicodin the same - vicodin 93 150

    Reply
  • Thanks code guru

    Posted by Nakro on 05/30/2013 12:08am

    We tried some of tips on www.tattoomix.com . Thank you very much for good article.

    Reply
  • Reason why everyone seems to be extremely wrong around shoes and also the reasons you have to read this review.

    Posted by BobHotgloff on 05/24/2013 09:55pm

    Basic fundamentals of of shoes that it's possible to cash in on commencing today. [url=http://www.shoesjp.biz/new-balance【ニューバランス】-c-670.html]newbalance[/url] The reasons pretty much everything you've found out about shoes is almost certainly drastically wrong and what you ought to realize. [url=http://www.shoesjp.biz/nike【ナイキ】-c-634.html]ナイキ[/url] A quick guide instructs you the ins and outs of the shoes combined with the things one need to do this afternoon. [url=http://www.kutujp.biz/]アシックス[/url] Creative shoes Book Reveal Guidelines On How To Rule The shoes Market [url=http://www.kutujp.biz/アディダス-adidas-c-4.html]adidas originals[/url] Why all kinds of things you may have discovered about shoes is truly drastically wrong and what you want to realize. [url=http://www.kutujp.biz/アシックス-asics-c-3.html]アシックス シューズ[/url] The best approach for the shoes that one could find out about this afternoon. [url=http://www.kutujp.biz/ナイキ-nike-c-13.html]ナイキ[/url] Progressive site reveal the low down regarding shoes in addition to the reason why you must take action straight away. [url=http://www.kutujapan.org/]ベルーナ[/url] Great new shoes Book Unveils Tips To Rule The shoes Market [url=http://www.kutujapan.org/adidas-アディダス-c-74.html]adidas[/url] Creative sneakers Publication Presents Method To Dominate The shoes Marketplace [url=http://www.kutujapan.org/new-balance-ニューバランス-c-13.html]ニューバランス[/url] Whatever the industry experts don't seem to be alleging in regards to shoes and the way that this can affect you actually. [url=http://www.kutujapan.org/nike-ナイキ-c-78.html]ナイキスニーカー[/url] The reasons why all people are extremely wrong in regards to shoes and the reasons you will have to see this review.

    Reply
  • The things that all the others actually does when it comes to nike and consequently specifically what youought to do totally different.

    Posted by icoppyapedcap on 04/22/2013 02:08am

    LbfFauBczTtf [url=http://www.adidasgekiyasu.biz/]adidas originals[/url]MlsWifTkxPrc [url=http://www.nikegekiyasu.biz/]ナイキ[/url]GqgEybFdbXgq IsmWsfNndKcu[url=http://www.guccisayihujp.biz/]グッチ 財布[/url]QpyOifGbdRhh [url=http://www.guccisayihujp.biz/【グッチ】レディース財布-c-5.html]gucci 財布[/url]PyzEboIvgKgs [url=http://www.guccisayihujp.biz/【グッチ】レディース長財布-c-6.html]gucci キーケース[/url]AniYktTmlTfc [url=http://www.guccisayihujp.biz/【グッチ】ショルダーバッグ-c-2.html]gucci アウトレット[/url]VjmXdqGhbPre OvjVuqDhnUtz [url=http://www.chloesayihujp.biz/]クロエ バッグ[/url] TiyBaxYyzZzj [url=http://www.chloesayihujp.biz/クロエ-長財布-c-3.html]クロエ 長財布[/url] IegBgvGhaDgt [url=http://www.chloesayihujp.biz/クロエ-ハンドバッグ-c-2.html]chloe バッグ[/url] FtfAwvUioPnm QxjYpuKjlQsf [url=http://www.chanelsayihujp.biz/]シャネル 財布[/url] KavEphYxeHqq [url=http://www.chanelsayihujp.biz/シャネル財布-c-9.html]シャネル 財布 新作[/url]TffIpdQbcXap [url=http://www.chanelsayihujp.biz/シャネル-ショルダーバッグ-c-1.html]chanel バッグ[/url]OgkCauUvdUnx

    Reply
  • Tips and Tricks on how to improve MVC Application Performance

    Posted by Robert on 04/21/2013 02:38am

    Hey Joydip Useful article, thanks We also had issues with slow performance with some MVC apps, so I put together a complete list with code examples to help developers improve permformance. Please take a look and let me know what you think: http://www.robertsindall.co.uk/blog/how-to-improve-mvc-application-performance/ Robert

    Reply
  • wholesale beanies

    Posted by xxds2dm on 04/01/2013 06:37am

    [url=http://snapbackswholesalezone.webs.com]snapback hats wholesale[/url] snapback hats wholesale b txap [url=http://snapbackhatwholesale.webs.com]wholesale snapbacks[/url] wholesale snapbacks l joaj[url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale i tcmr[url=http://snapbackswholesalezone.webs.com]hats wholesale[/url] hats wholesale m dnjt[url=http://snapbackhatwholesale.webs.com]wholesale beanies[/url] wholesale beanies e yelq[url=http://snapbackswholesalezone.webs.com]fitted hats wholesale[/url] fitted hats wholesale l ayoc [url=http://cheapsnapbackshat.webs.com]cheap snapbacks online[/url] cheap snapbacks online o iago [url=http://bestbaseballcap.webs.com]wholesale hats[/url] wholesale hats u nryp[url=http://cheapsnapbackshat.webs.com]cheap hats for sale[/url] cheap hats for sale c farg[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping p gmfu[url=http://wholesalefittedhat.webs.com]wholesale fitted hats[/url] wholesale fitted hats n uigw[url=http://cheapsnapbackshat.webs.com]cheap hats[/url] cheap hats e zfgv [url=http://bestbaseballcap.webs.com]wholesale baseball caps[/url] wholesale baseball caps z pufa [url=http://snapbackhatwholesale.webs.com]wholesale fitted hats[/url] wholesale fitted hats x occk[url=http://cheaphatsmall.webs.com]cheap hats[/url] cheap hats b txcc[url=http://cheapsnapbackshat.webs.com]cheap hats online[/url] cheap hats online r blad[url=http://snapbackhatwholesale.webs.com]wholesale fitted hats[/url] wholesale fitted hats b iyrf[url=http://cheapsnapbacksforsalezone.webs.com]cheap snapbacks free shipping[/url] cheap snapbacks free shipping e wufg

    Reply
Leave a Comment
  • Your email address will not be published. All fields are required.

Top White Papers and Webcasts

  • Live Event Date: December 11, 2014 @ 1:00 p.m. ET / 10:00 a.m. PT Market pressures to move more quickly and develop innovative applications are forcing organizations to rethink how they develop and release applications. The combination of public clouds and physical back-end infrastructures are a means to get applications out faster. However, these hybrid solutions complicate DevOps adoption, with application delivery pipelines that span across complex hybrid cloud and non-cloud environments. Check out this …

  • Hundreds of millions of users have adopted public cloud storage solutions to satisfy their Private Online File Sharing and Collaboration (OFS) needs. With new headlines on cloud privacy issues appearing almost daily, the need to explore private alternatives has never been stronger. Join ESG Senior Analyst Terri McClure and Connected Data in this on-demand webinar to take a look at the business drivers behind OFS adoption, how organizations can benefit from on-premise deployments, and emerging private OFS …

Most Popular Programming Stories

More for Developers

RSS Feeds