Use ViewModels to simplify the View.
For instance, you might have a deep object graph with Products, Order, Customers, etc - and some information from each of these objects are required on a particular View.
A ViewModel provides a way to aggregate the information required for a View into a single object.
ViewModel's also allow for things like data annotations and validation - which does not belong on your model, as your model should stay "domain-specific".
But in reality, ViewModels are nothing more than a simple wrapper for your domain objects.
Use a tool like AutoMapper to map back and forth between your ViewModels and domain models with ease.
Personally i always bind to ViewModel's in my View's, never to the domain models, even if it's a single object. Why? Well i like to decorate my ViewModels with UIHints, validation, data annotations. Just the same way your domain models are enriched with domain-specific rules and business logic, so should your ViewModels be enriched with UI-specific logic.
If you simply have a object with a 1-1 representation of your domain model, you are missing the point of ViewModels.
Add to the ViewModels only, and nothing more, what is required for a particular View.
Example controller action
public ActionResult CustomerInfo(int customerId)
{
// Fetch the customer from the Repository.
var customer = _repository.FindById(customerId);
// Map domain to ViewModel.
var model = Mapper.Map<Customer,CustomerViewModel>(customer);
// Return strongly-typed view.
return View(model);
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…