Facilitating the Spread of Knowledge and Innovation in Professional Software Development

Write for InfoQ


Choose your language

InfoQ Homepage News ASP.NET MVC and Codebehind Files

ASP.NET MVC and Codebehind Files

This item in japanese

The ASP.NET MVC community discusses, if codebehind files are still needed when using the WebFormsViewEngine and whether they are a benefit or a disadvantage or even a problem.

ASP.NET MVC still uses the WebFormsViewEngine by default. When adding a WebForms view to an ASP.NET MVC application Visual Studio adds a codebehind file and a designer file automatically. Many people think that codebehind files are obsolete and that their usage is rather confusing, since developers might tend to use views like traditional all-in-one ASP.NET web forms.

Steve Smith goes a bit further and proclaims that Codebehind Files in ASP.NET MVC are Evil, because  they tempt developers to add logic to views, which should stay “dumb” by design:

Having a codebehind file is a temptation.  Developers who are new to ASP.NET MVC (and who isn't - it's not even a year old and not released yet) but who have a background with web forms (as most will) are going to have to resist a natural inclination to put code into their codebehind files like they always have.  This will make the logic in the View more difficult to test and at worst might even involve logic in the codebehind making calls directly to a database or web service and thus completely bypassing the separation of Model from View as well.

Steve explains that in some cases codebehind files are a necessary evil, e.g. if you want to have a strongly typed view in order to reference the model in a strongly typed way. Some argue that codebehind pages might also be used to store some view logic, which otherwise would clutter the ASPX file. And last but not least they are technically needed in order to get intellisense on the ASPX files. Regarding the first issue, Tim Barcz shows how to use Strongly-Typed ViewData Without A Codebehind by incorporating the CLR notation for generics instead of the C# or VB notation:

Inherits="System.Web.Mvc.ViewPage`1[[ABCCompany.MVC.Web.Models.LoginData, ABCCompany.MVC.Web]]"

The CLR notation defines the generic parameters count after the apostrophe followed by the parameters and the assembly containing the parameters’ types.

Luis Abreu disagrees with Steve and responds in a post. He is “not sure that removing the codebehind file will be enough for stopping a ‘bad’ programmer”, because logic could still be placed within script blocks in the ASPX file. Luis also disagrees with the general ideas of “dumb” views. In his view views may incorporate “presentation related code” and this code should be placed in codebehind files rather than in controllers or in the ASPX file directly, which would destroy the clear separation between markup and code.

Rate this Article