4

I'm trying to learn about MVC and I'm confused about where to put business logic.

All the web applications I've built have been using N-tier architecture and because of this I'm used to putting business logic and database interaction in their own classes/respective 'layers', but how does this work in MVC?

From what I've gathered so far, it seems that this should all be stored in the Model? But I'm confused, because it seems it could just as easily be stored in the Controller? The Controller is responsible for returning the appropriate View.. so wouldn't it make sense that all the logic is stored here?

If anyone could just give me an idea of best practices in this situation I'd be very grateful.

Thanks!

alimac83
  • 2,346
  • 6
  • 34
  • 50
  • 1
    check my answer and the comments here: http://stackoverflow.com/a/7474357/559144 the M (Model) of MVC should NOT be confused with the Entity Model of EF or whatever ORM you are using. if you do so you create a strong dependency between UI layer and DAL. I suggest you to layer the project like described in my answer there. – Davide Piras Feb 16 '12 at 10:53

1 Answers1

5

The Controller should call your Business Layer and then creates a simple POCO ViewModel to pass it to the View.

For example.:

  • Your Controller calls the BusinessLayer to get a User from Database.
  • He gets back a User Model WITH logic.
  • Then he creates a UserViewModel which has only properties and pass it to the View

Because one major thing about MVC is seperation of concern. You should create a ViewModel that has only the data your View needs, no logic.

A ViewModel is just a simple POCO class (Plain Old CLR Object, a class that only has properties, no logic)

More Information

Community
  • 1
  • 1
dknaack
  • 60,192
  • 27
  • 155
  • 202
  • So am I right in thinking that the Controller's responsibility in an MVC app is very limited? Most of the code will be found in the model and the Controller just handles shifting this data to the appropriate view? – alimac83 Feb 16 '12 at 10:59
  • Yes right, think that the controller is between the View and the Model. View <> Controller <> Model. The logic is in the Model (in your Business Layer) the Controller "talks" with the layer and translates the result to a ViewModel. Be aware of the difference of the Model and the ViewModel. – dknaack Feb 16 '12 at 11:02
  • Will do.. just waiting for the time to expire before I can select it :-) – alimac83 Feb 16 '12 at 11:05