2

In an Model-View-Controller (MVC) design pattern, What goes where? What code goes to model and to controller?

I know (do I?) that business logic should be define in a model, but a lot of example I find on the internet only use the model to define the data. Take Microsoft's example of model for instance, it only writes it this way:

using System.ComponentModel.DataAnnotations;

namespace MvcMovie.Models
{
    public class Movie
    {
        public int Id { get; set; }
        public string? Title { get; set; }

        [DataType(DataType.Date)]
        public DateTime ReleaseDate { get; set; }
        public string? Genre { get; set; }
        public decimal Price { get; set; }
    }
}

Then defines the business logic on a controller...

public async Task<IActionResult> Details(int? id)
{
    if (id == null)
    {
        return NotFound();
    }

    var movie = await _context.Movie
        .FirstOrDefaultAsync(m => m.Id == id);
    if (movie == null)
    {
        return NotFound();
    }

    return View(movie);
}

Meanwhile...

I worked with an MVC project with my friend before back when I'm still a student and on his code, all the business logic such as interacting with the database are done in the model and not on the controller.

I'm working on my personal project right now and I'm writing my database interaction on my model. Am I right?

So,... What really goes where???

4
4

You are fully right on the principle. The MVC should have the business logic and the data access layer in the Model. The Controller should manage user input and transforms it into commands either for the View or for the Model. There should be no business logic in an MVC controller.

But the code snippet you show from the controller does not seem to infringe this segregation of concerns: It‘s not business logic, but a query of the model to create a view. So typically the coordination things that an MWC controller does.

You may be confused to think that it accesses the DB directly. But it appears that _context is not a db context, but an MvcMovieContext, i.e. an object that is part of the model. It uses the result to create a View.

But for the clarity of the tutorial we could indeed regret that the

  • MvcMovieContext inherits from a DbContext, a shortcut that might leak some implementation details outside the model.
  • The separation of concerns does not fully match the classical MVC. In the original MVC, the logic would be to create a view and passing it the id, and let the view query the model (and the model notify the view if data changes). In this regard, your snippet‘s approach looks more like an MVP to me, where P is the mediator between model and view.

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.