3

In ASP.NET MVC, Where should one work with view models?

Should this be done strictly in the controller? Or would it be ok to say, return a view model from a repository method?

4 Answers 4

6

To my mind viewmodels are specific to whatever application is going to use them, whereas a repository would return a model common to all applications. So I'd say the view model should be created within the web site, from a common model returned from the repository, rather than tie the repository into knowing about how views are laid out.

1
  • What if two applications could use the same ViewModel? Would you create a dedicated project for the VM then? Commented Oct 19, 2016 at 16:31
3

Strictly speaking your repository should return domain objects

Repository: "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects."

Fowler (PoEAA)

1

Viewmodels should be instantiated in your controller and passed to the strongly-typed view. Typically a ViewModel will contain multiple model types necessary to render your view. Here's a Quick Example:

Say you have two model objects Orders and Customer

You want to display Customer Details at the top of the page and a Grid of Orders in the Index view for that customer.

public class CustomerModel
{
    //properties
}

public class OrderModel
{
    //properties
}

public class CustomerVM
{
    public CustomerModel customer { get; set; }
    public IEnumerable<OrderModel> orders { get; set; }
}

//and in your controller

public class CustomerController : Controller
{
    public ActionResult Index(int id)
    {
        CustomerVM vm = new CustomerVM();
        vm.customer = CustomerRepository.GetCustomer(id);
        vm.orders = OrdersRepository.GetOrdersForCustomer(id);
        return View(vm);

    }
}
0

repository should be a in between your domain and UI - the repository should know nothing about your UI layer - so you can get the best re-use and decoupling from it as possible.

Your Answer

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

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