ASP.NET MVC and Codebehind Files
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.
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:
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.
Its optional -anyway-
That said, those MVC views are cute and pretty in demos and prototypes, but when you start going hardcore and make full scale applications, even when using partial views, it will get cluttered REALLY fast... code behind will help in that situation... So the option should stay there IMO.
Re: Its optional -anyway-
Mike Hartington Jul 26, 2015