SKale
SKale

Reputation: 571

Which code is more of a correct MVC approach? Put code in controller or ViewModel?

I have read that in an MVC application one should keep controllers "thin". But when I put code to fetch data in the ViewModel I feel it's less intuitive to locate, meaning when I am troubleshooting I generally tend to look in my controller first (or maybe that's my real problem). Also I find one can reuse the same VM for many different things if you pass data through the controller.

Am I violating some big principle or causing performance issues?

For example, compare these dummy snippets with two approaches, both seem to work just fine:

Assume a Repository called repositoryy with a method GetCourses() that fetches a list of Courses.

1) ViewModel fetches the data and controller directs traffic:

public CourseViewModel
{
    private MyProjectEntities db = new MyProjectEntities();
    Repository repository = new Repository();
    {
     public CourseViewModel()
        {
          Courses = db.Course.ToList();
        }
    public List<Course> Courses {get; set;}
    }
}

public class CourseController : Controller
    {
    public ActionResult Index()
    {
     var courseviewmodel = new CourseViewModel();
     return View(courseviewmodel);
    }
}

2) Controller fetches data, passes to ViewModel and then to the View:

public CourseViewModel
{
     public List<Course> Courses {get; set;}
}


public class CourseController : Controller
{
    public ActionResult Index()
    {
     var courseviewmodel = new CourseViewModel();
     courseviewmodel.Courses  = repository.GetCourses.ToList();
     return View(courseviewmodel);
    }
}

Upvotes: 0

Views: 45

Answers (1)

MikeSW
MikeSW

Reputation: 16348

The second option. Btw there's no 'more correct MVc approach'. There is the MVC separation and that's that. Your first option breaks that separation, because the view model does the controller's work instead of being the 'dumb' dto holding the view's data. You don't want to couple the view model to the model.

In MVVM though, the view model acts a bit like a controller, however that approach is best suited for desktop aps, not web apps.

Upvotes: 2

Related Questions