Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Code-Behind with ASP.NET MVC Views

Tags:

asp.net-mvc

Is it considered a bad practice to use code-behind with ASP.NET MVC Views? Got into a bit of a debate about this with my colleagues today and I was wondering the community's thoughts.

Obviously, this isn't an option when using another MVC like Rails, which makes me think it's relied on more as a crutch for those accustom to working with traditional ASP.NET Web Forms applications.

like image 960
jamesaharvey Avatar asked Oct 13 '09 20:10

jamesaharvey


People also ask

What is the purpose of code behind in asp net?

If you use code-behind class files with . aspx pages, you can separate the presentation code from the core application logic (or code-behind). The code-behind class file is compiled so that it can be created and used as an object. This allows access to its properties, its methods, and its event handlers.

Can we use TempData in view?

TempData is a property in the ControllerBase class. So, it is available in any controller or view in the ASP.NET MVC application. The following example shows how to transfer data from one action method to another using TempData.

What is present in code behind view class?

Code Behind refers to the code for an ASP.NET Web page that is written in a separate class file that can have the extension of . aspx. cs or . aspx.

Can ViewData pass data from view to controller?

You can use ViewData to pass data from controllers to views and within views, including partial views and layouts.


2 Answers

I would say that it's a bad practice to use code-behinds with ASP.NET MVC. MVC allows separation of concern where presentation logic (in Views) are separated from application logic (in Controllers). Using code-behinds will mix presentation logic and application logic inside the code-behinds, whereby defeating some of the benefits of MVC.

like image 180
Johnny Oshika Avatar answered Oct 02 '22 15:10

Johnny Oshika


Certainly the authors of ASP.NET MVC In Action advise against it, and I agree. It isn't necessary, so why do it? In the early betas a code-behind file was included, but this was removed at RTM (or shortly before).

Typically, it simply encourages you to do more non-view work than you should in the view, as it is out of sight / out of mind.

like image 39
Marc Gravell Avatar answered Oct 02 '22 15:10

Marc Gravell