0

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:

View:

Boo boo = new Boo("awesomness");
Controller.AddDB(boo);

Controller:

public void AddDB(string name)
{
 Boo boo = new Boo(name);
 addtodb(boo);
}
asked Nov 21, 2013 at 21:21

2 Answers 2

4

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.

answered Nov 21, 2013 at 21:33
2
  • 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) ? Commented Nov 21, 2013 at 23:22
  • @Nikola I updated my answer Commented Nov 22, 2013 at 8:04
0

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.

answered Nov 22, 2013 at 0:30

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.