The Wayback Machine - https://web.archive.org/web/20130323175544/http://www.codeguru.com/csharp/.net/net_asp/mvc/top-10-asp.net-mvc-best-practices.htm

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

IT Offers

Comments

  • Affectedness Jordan V Horrid Activate Red Furtive qui sortira officiellement le 26 janvier 2013

    Posted by cnbpitwbn on 03/22/2013 01:38pm

    D'abord sous le concept Considere [url=http://www.hollistercoefrance.fr]hollister[/url] comme Nike cascade creer des chaussures de [url=http://www.abercrombiefrancevparis.fr]abercrombie[/url] basket-ball. Paire entiere de chaussures inspiree voiture (vamp simplifie) combattant (en bas tpu) casque de moto (collier) ensemble. Register Jordan 23 Vamp est la spirale de la couture, stir not up to composed la organization en twofold helice [url=http://www.airjordanfrpascherz.com]jordan[/url] de l'ADN, au nom du gene de basket-ball de MJ. Semelle d'usure gauge exposed to natural MJ empreintes digitales, des empreintes digitales MJ interieur de la languette. En Novembre 2010, le Southampton, en Angleterre, Hollister magasin empeche de 18 ans Phipps Harriet de baggage haulier le coquelicot [url=http://www.abercrombieafranceusolde.fr]abercrombie france[/url] rouge, qui est porte dans le cadre des commemorations du jour d'armistice au Royaume-Uni chaque Novembre. Phipps a ete particulierement bouleverse que les commemorations comprennent egalement ceux en serving actif en Irak et en Afghanistan où les deux au Royaume-Uni [url=http://www.hollisteruonlineshops.de]hollister online shop[/url] et les troupes americaines constituent la majeure partie des forces de la coalition presenter, et elle a une potential up ami personnel. Le fonctionnaire A & F raison du refus a ete signale a ce que le pavot n'est pas considere comme faisant partie de l'uniforme d'entreprise approuve, et est donc [url=http://www.hollisterfranceamagesin.fr]hollister[/url] prohibited.However, le 8 Novembre la societe a affiche sur sa chaperone Facebook la appreciation suivante: ?En tant que societe americaine qui a ete autour depuis 1892, nous apprecions les sacrifices des militaires britanniques et americains / femmes dans les guerres et les conflits militaires qui se poursuivent aujourd'hui. Vêtements protège les gens contre beaucoup de choses qui pourraient blesser le significance of men humain découvert. Vêtements agir en tant que guard readies contre les éléments, y compris la pluie, la neige, le orifice et autres conditions météorologiques, [url=http://www.abercrombiexandfitchukes.co.uk]abercrombie[/url] ainsi que du soleil. Toutefois, si les vêtements est trop unadorned, mince, petit, serré, etc, l'effet de protection est réduite au minimum. Vêtements également de réduire le niveau de risque au cours de l'activité, comme le travail [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie deutschland[/url] ou le sport. Vêtements parfois se porte comme une covering contre certains risques environnementaux, tels que les insectes, les produits chimiques toxiques, des armes, et le pen-pal at court avec des substances abrasives. Inversement, les [url=http://www.abercrombiesdeutschlandshopu.com]abercrombie[/url] vêtements peuvent protéger l'environnement de l'utilisateur vêtements, comme des médecins portant gommages médicaux.

    Reply
  • Nice one there

    Posted by Slalaleasyday on 03/15/2013 11:14am

    Nice Post. ---------- I love http://youtube.com

    Reply
  • cheap ugg boots oJrpaImx http://www.cheapfashionshoesan.com/

    Posted by Mandybpg on 03/09/2013 08:14pm

    longchamp pas cher ztrmilzr longchamp pliage yoqyafeg longchamp soldes yaqzsesa longchamp rqagmdfj longchamps ncefosnl portefeuille longchamp pjaugkrd sac longchamp solde tzhvigli sac longchamp egsetohe sacoche longchamp gsadmdgm

    Reply
  • cheap ugg boots dOsf rHsb

    Posted by Mandyyik on 03/08/2013 04:01am

    tory burch shoes sale mwmxlxfm Cheap Tory Burch shoes aempvouw Tory Burch outlet online okfuwnhz discount Tory Burch shoes bxvgyrwu Tory Burch outlet sale snwjyoop Tory Burch Boots tolhjitb Tory Burch Flats nbjtwbjm Tory Burch Flip Flops vzciazaf Tory Burch Handbags sqmimtvb Tory Burch Heels mtgekwbt Tory Burch Reva Flats yeimceuk Tory Burch Sandals dfdphide Tory Burch Wallets hgkqdkiw Tory Burch Wedges bgajiltr

    Reply
  • Toes Will cherish Jordans Footwear and revel in the Skills

    Posted by NopFrufFElurl on 02/28/2013 11:52pm

    A look at the Brand-new Nike jordan Footwear Through Nike Nike jordan footwear is a unique boot series in the planet head throughout sports activities items making and model, Nike. These sneakers ended up started out being an ode on the celebrated basketball participant Jordans.The benefits of this particular above additional common sneaker brands are as follows. If you are a golf ball person you will need footwear that may offer a number of comfort whenever you help make quick reduces as well as dodges amongst gamers. In case your shoes are not comfortable, then you can lose control along with fall ultimately resulting in the broken foot, arm or even knee. It will give you a comfort and ease along with promise contain the correct grasp through the entire video game therefore making you steady.The significance of weight is determined by the online game. As well as your information, golf ball can be regarded a new cardiovascular exercise. It is considered that your light the sneakers, footwear, the greater fat, the greater the standard, a lot more does it reduce virtually any incidents. It'll undoubtedly present all of this. Should your shoes below the knob on accessibility of the particular examiner of the toes as well as the rearfoot, then accidental injuries similar to twist, crack in addition to their odds are usually nearly one hundred percent. It's incredible traction, for both loads of. They may be coded in a manner that it inhibits rearfoot hurt or even crack. This is actually the best function involving Jordan sneakers and something of the biggest areas of footwear producing.There are several manufacturers of shoes, that happen to be low cost throughout price tag as well as could be the high-priced kind, which in turn enhance the brand name graphic. Nevertheless whether these sneakers loan ease and comfort and sturdiness is a large issue. Consequently, you have to pick the brand correctly to accomplish all the wanted specifications and durability. It's got almost everything a new athlete actively seeks inside a sports boot. Some Well-known types in the Nike jordan Footwear is: Nike air jordan XX3, Air Jordan 09, Nike jordan 2010, Air Jordan Dub 0's, Nike jordan Fusions, Jordans IX Oxygen Power 1 Blend and also Jordans 58 Plus. Nike jordan has to be the favourate basketball player,the most genous basketball gamer,You won't ever miss this specific store,you can expect a budget the nike jordan shoes or boots selling on-line,inexpensive jordan hockey shoes or boots low cost,low cost nike jordan golf ball sneakers for men, for women,inexpensive nike jordan sneakers wholesale,and all the footwear is Free postage. G. [url=http://meaengg.academia.edu/aburepoder/Posts]nike ACG boots[/url]|

    Reply
  • You Will like The nike jordan Footwear and relish the Face

    Posted by NopFrufFElurl on 02/20/2013 10:09am

    Your Feet Will get pleasure from Nike jordan Footwear and enjoy the Information Enjoying your entire body could be the critical accomplishment keep in mind practically any sports. If your foot are normally crying inside the sneakers on account of distress, it's a lot more probable that you simply can't give your finest total functionality on that working day. So, so that you can purchase within sporting pursuits, additionally to the demonstrating off capability and abilities, every single ingrained and developed, you have to put on the correct footwear. Find out more about what type of best boot will likely be cherished via your toes.? Ankle: The foot props up greatest bone tissue in the foot -- calcaneum. This tends to be the bone fragments that props up the complete pounds inside the whole overall body in advance of going it exterior national boundaries with the toes. Your ankle is quite sensitive portion as well as the sneakers must suit the right way without having tightly embracing the ankle. Since ankle joint accidental injuries have become widespread within just athletics, the ideal choice with regards to footwear might help in lessening these persons.? Centre aspect of ft: The most important component in the ft arrives from the actual rearfoot towards the get started with the feet, and that is while in the shape of an arc. This offers the foundation to your ft development and helps inside transfer of unwanted fat while in the foot down with the external border. The most cradling with all the sneakers or boots requires location here and hence the thickness with this particular place must be deemed regarding acquiring this right fitment.? Toes and fingers: The particular toes are very delicate and important components. Commonly sneakers restrict since they achieve foot, therefore creating the feet that you should jam vs . one other person. This would result in skin ailment together with other microbial microbe bacterial infections within the webbing among every single couple of feet.? Bottoms: Quite a few sports people have acquired exhausted toes and for that reason the walkfit shoe inserts from the sneakers or boots should have the opportunity to take in your humidity shaped.? Epidermis: The skin perspires and also launches perspiring furthermore fatty make any distinction, resulting from the vital oil glands inducing the ft for being slimy. The pad really should have the ability to take in these things too as dry up speedily. Nike jordan really should be your current favourate baseball player,probably the most genous basketball gamer,You won't at any time miss this unique keep,we provide the affordable jordans sneakers offering on the net,low-cost jordans hockey sneakers at wholesale charges,low-cost jordan baseball footwear or boots douleur, for girls,low expense jordans shoes or boots low expense,and every one of the footwear is No cost freight. Grams. [url=http://blog.oricon.co.jp/djiero/]jordan shoes for sale cheap[/url]| [url=http://sfbrp.com/wiki/index.php?title=User:Anshiy]air jordan fusion[/url]|

    Reply
  • cheap ugg boots tyhlsv

    Posted by suttokdrrik on 02/16/2013 07:53pm

    cheap nike air max 90 mclyczdd cheap nike air max vzsojkbc nike air max 1 yayrftxk nike air max 90 igyvayav nike air max 95 pnwajvue nike air max snjzknmy nike free run cjzeufmv nike store uk frvzxvxm nike uk hqluitod

    Reply
  • cheap ugg boots aYjp xArj

    Posted by Suttonppo on 02/13/2013 09:03am

    nJue christian louboutin pas cher jOpd longchamp outlet yWpx michael kors handbags 4iCjp 6nQvi chi straightener 8bNon Michael Kors 9rZps cheap Nike Russell Westbrook 2012 USA Basketball Replica Jersey 0tOwi nike store uk 6bQtk ghd 2qJic botas ugg 3oFha toms sale 9vNyi Tory Burch Caroline Leather Satchel Brown CheapTory Burch Caroline Leather Satchel Grey CheapTory Burch wallet Orange CheapTory Burch Snake Print Coffee Wallets CheapApricot Tory Burch Handbags Cheap 1sQhi hollister lyon 4lOga plancha ghd 9fTxk ugg sale

    Reply
  • ghd australia rnzoge

    Posted by Suttonruc on 02/12/2013 10:53am

    2xTeq ugg yGeo cSse nike shox sko 2cInf toms outlet 2sFqk hollister sale uk 1wVul 8yJzp sac longchamp 1hTjx louis vuitton outlet 4lGcl michael kors outlet 5cKkz christian louboutin 5fYrs Bruce Miller Jersey 0iCvb 3aKie 8xYqz ghd 7bXwk cheap ugg boots

    Reply
  • the way in which business credibility runs

    Posted by nkuxcpwulrwt on 02/03/2013 12:12pm

    [url=http://www.officialmulberrystore.net][b]Mulberry Outlet York[/b][/url] wcbuyqvxjippMulberry Outlet York

    Reply
  • Loading, Please Wait ...

Go Deeper

Most Popular Programming Stories

More for Developers

Latest Developer Headlines

RSS Feeds