Wednesday, 11 April 2012

ASP.NET MVC3 Attributes

I am currently working on a project where we're porting an existing SharePoint 2010 site to ASP.NET MVC3. Coming from an ASP.NET Web Forms background, this is an interesting experience. ASP.NET MVC is quite different from the Web Forms model, with one of the biggest differences being its emphasis on "convention over configuration".

Having played with MVC2 in the past, the work on this project has been smooth sailing. I'm particularly enjoying the level of control that the MVC development model provides over the resulting HTML sent back to a users browser. The bloated HTML from the Web Forms model (quickly pointing the finger at the ViewState hidden field) is something I don't have to painfully scroll over when inspecting the generated HTML.

I particularly like how MVC makes use of attributes on action methods, things like the AuthorizeAttribute are a nice and clean way of executing repeated functionality without it really getting in the way of your usual controller or action level logic.

The main purpose of this post is therefore just for me to continuously document the useful attributes I come across. My intention is to update the table below whilst working on the project mentioned above.

Attribute Name Notes
System.Web.Mvc.AuthorizeAttribute Applied on actions that require the user to be authenticated. If the user is not authenticated, they are automaticallly redirected to the login page. Can also be used at the controlller (class) level - which applies it on all actions within the controller.
System.Web.Mvc.ChildActionOnlyAttribute Applied on actions that shouldn't be invokable directly through the browser. Use this when the action returns inline HTML markup e.g. partial views. Can only be called via Action or RenderAction HTML extension methods.
System.Web.Mvc.NonActionAttribute Use this when you don't want the MVC framework to treat a method in your controller class as an action. By default, the framework will treat all public methods in a controller as an action method.
System.Web.Mvc.OutputCacheAttribute Used to cache the output of an action. Has a number of useful named parameters, one of which is "Duration" that lets you specify the number of seconds to cache the output for.