I am using the MVC pattern.

Lets say I want to create a new object and add it to my database.

Where is it better to create the new object:


Boo boo = new Boo("awesomness");


public void AddDB(string name)
   Boo boo = new Boo(name);

The view never directly acts on the model layer. It only uses objects provided by the controller for display. It should not even run read queries, by no means it should ever do anything itself that changes the state of the database.

I use MVC in a web environment where ctrl.Add(new Customer(name, age)) would not be an option anyway. But the view should really have no knowledge about models. Assume it would not only be name and age but you would also want to provide an address. For now all of this is stored in a single customer table. Later you decide that you want to have addresses stored separately. That would be one example why you would not want to have the view to decide what objects to create.

Depending on language and environment the question of object ownership and lifetime would be relevant too. You don't want to spread this over several places where it is not really needed. This especially in languages that do not have garbage collection and the decision when and where to free the objects memory becomes relevant too.

| improve this answer | |
  • Well my Viewer is basically my GUI. If I decide to create a new customer for example, how would I send it to the controller to add it to the database? ctrl.Add(new Customer(name, age)) or ctrl.Add(name, age) ? – Nikola Nov 21 '13 at 23:22
  • @Nikola I updated my answer – thorsten müller Nov 22 '13 at 8:04

If the model needs updated, this has to be done in the controller--that is, after all, where the actions of the system are contained. In ASP.NET MVC (since you don't specify what kind of MVC you are using), you POST the data back to an action which takes the model and would call some sort of database command (be it through an ORM, stored procedure, or inline SQL call).

Doing any of this in the view would violate the separation of concerns that you establish by using an MVC architecture.

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.