开发者

Where should viewmodels be created/manipulated in asp.net mvc?

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

Should this be done s开发者_JAVA百科trictly in the controller? Or would it be ok to say, return a view model from a repository method?


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.


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)


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);

    }
}


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜