tags:

views:

490

answers:

4

I prefer strongly typed viewdata for my asp.net mvc views for various reasons and I actually preferred the Views with codebehinds as they were in the earlier asp.net mvc previews because the codehind was a natural place to define the poco viewdata class as they generally have a 1:1 relationship with the actual view.

Are there any way to have the codebehind in asp.net rtm views or is this not a good approach?

EDIT: The only reason I would like to have codebehind is that I see the ViewData as a property of the view. If the view was a class then the ViewData was one of its properties and it feels un-natural to define this in a separate assembly.

+6  A: 

After almost a year together with MVC I can confirm I have not needed code-behind for views even once. If you use code-behind you're likely still thinking WebForms. Drop it.

Views should be there to just display the model data. Simple decisions like what CSS class to apply can be performed directly in the view within server tags. More complex decisions should go to the controller or business logic.

Developer Art
But do you use strongly typed viewdata, and in case where are you defining those classes?
TT
Those classes should be in their own assembly - MyProject.Models and, for larger projects, MyProject.ViewModels (or .DTO).
Jason
@TT: Yes, I use strongly typed views. I keep the models in "Models" folder. Models basically represent a separate thin layer that holds the prepared data for a view to display.
Developer Art
I guess I just got hung up on the physical placement of the ViewData classes, but having them in the Models folder makes sense. Thx
TT
A: 

Having codebehinds for Views goes against one of the purposes of an MVC framework.

The View should be as simple as possible and only focus on presentation while letting the Controller or Extensions handle all the business logic.

Those with the combination of ViewState should remove the need for codebehinds.

skalburgi
A: 

There is no need for code behind in MVC architecture as it was with Web Forms.

The entire MVC architecture build on the controller controlling the stuff and not the webcontrol events doing the magic.

Personally I am just getting into the dark side of MVC but I like what I see here now.

You can easily put content on your view with the "return View(item)" in your actions -> where item can be strongly typed data and easily validate it in your model. (which is great since input errors will be displayed on the view)

Shaharyar
+1  A: 

I prefer strongly typed viewdata for my asp.net mvc views for various reasons

This can still be done ofcourse. NerdDinner FormviewModels page 6 I use it and it works perfectly. Had some problems which you can find in my two questions here and here .

As said above, I do not see why you would want to use codebehind. If you want that I recommend you read the general information about the MVC structure and what views are for.

bastijn