views:

135

answers:

3

I have a question regarding keeping the controller and view separate. It seems to me that the controller should only pass a model to the view, and the view decides how to display the model. This way, the controller and model stay separate and can be independently developed. However, a lot of tutorials I see online and even in the book Pro ASP.NET MVC Framework, I see a lot of examples using either ViewData["string"] or TempData["string"].

Doesn't this introduce two problems? The first one is that the view is now somewhat coupled to the controller in that it has to know the name of the strings that the controller is setting in ViewData/TempData. The second is that these are loosely-typed, meaning there's no Intellisense. If I was developing the controller, I can't just tell another developer working on the view to just use Intellisense for the model, I'd have to give him the name of the strings, and if I ever change the string names, I'd also have to change it in the view.

I guess ultimately what I'm asking is, is this right? Or am I not understanding something?

+1  A: 

Yes you are right, it's considered best practice to create a class often called ViewModel that is being sent to/used in the View. The ViewModel usually contains the model as well as any other data the view might need, such as page number for a paginated list view, or values for a list for the view to display.

svinto
+4  A: 

Hi

View Data is one of the a way to pass information between the view and the controller but, as you said, there's no intellisence and it increase coupling. Instead, you should consider using a ViewModel. See Scott Gu NerdDinner example (freely available) about the way to use ViewModel and about the pros and cons of ViewDate vs ViewModel.

I hope it will help.

mberube.Net
Thanks for the answer! All of you guys basically said the same thing, but unfortunately I can only mark one as the answer, so I gave it to the guy with the lowest reputation score.
Daniel T.
Thanks a lot helping the newbie !
mberube.Net
+2  A: 

I think that the tutorials and book are using this method to try and make things a little easier to start out. However, I my opinion is that this might be starting some bad habits as you suggest.

The way I do it roughly based upon this article by Jimmy Bogard:

  • All views are strongly-typed
  • One specific ViewModel class per View
  • The View determines what data is in the ViewModel

I don't use the Auto-Mapper as he does though. I usually use a utility method to convert my Model object to the associated ViewModel object.

81bronco