In working with MVC I am finding my Views to be rigid in terms of their associated Model definition. Should I design my Models around the needs of my view? I realize I can create a container specifically for my view. Then design a second Model in terms of Entities. But, it appears that I always need this stand-between. I mean, there's even a @model
to declare what the View is supposed to be coupled to.
For example, I have a View with two tables. The tables both work off the same开发者_高级运维 Entity, so it doesn't make sense to use that Entity as the Model. Rather, the Model needs to be a wrapper that contains 2 of said entities. Moreover, the entities really need to be converted to string[]
in order to avoid data massaging in the View.
Am I just too much of an MVC nublet, or is this how MVC is designed to work? Tight relationship with View-Model.
Use a ViewModel for your views. It's bad practice to associate your View with the Model that comes directly from EF.
public class ProductViewModel
{
public ProductViewModel(List<Product> products, List<Category> categories)
{
this.Products = products;
this.Categories = categories;
}
public List<Product> Products { get; private set; }
public List<Category> Categories { get; private set; }
}
ViewModel Best Practices
ASP.NET MVC View Model Patterns
Typically, and I think a lot of the SO/MVC community would agree that following a View Model-esque pattern is extremely beneficial even in the case you're describing. Wrap your entities in a view model class and bind it in the @model
statement at the beginning of the view.
The Microsoft guys have recommended the same, though it's not absolute law.
It seems extremely tedious at times, but unless you're writing your own view engines combined with some super advanced model binding logic, the easier path is typically found to be view models. Add more tediousness with data annotations for validation, etc. But to be honest, if advanced model binding and custom view engines are required, your problem has probably been given too much thought.
I agree, don't pass entity classes straight to models. Use your view models to call service or BL classes which assemble the data entities from the data store. I've found the most flexibility when using 1 view per view model, period. To reiterate, that is a 1:1 ratio between view model classes and views. Even if the views have to be broken down into manageable pieces, use display and editor templates to accomplish what you need. It'll help you out later :)
精彩评论