Does using ViewModels and references to System.Web.Mvc violate the MVC pattern?
I've seen it all over SO, blogs, and book开发者_StackOverflows, where the authors tell you add ViewModels specific to your View in your Model projects as wrappers for your underlying model objects. The idea is to make it very simple and targeted when you go to do model binding to the View. Here is a good example: Rendering and Binding Drop Down Lists using ASP.NET MVC 2 EditorFor
However, it irks me a little that there are references now to System.Web.Mvc in my model, which otherwise could have been used for multiple outlets (maybe WCF API, Silverlight, etc), but now I have specific references to MVC dll's that will be required to get my model project to build.
My question is: does this violate MVC patterns when we start adding IEnumerable<SelectListItem>
to our model classes? And is there a viable alternative layer to move this to and how, ie Controller?
Any thoughts or comments appreciated.
I personally only create the select list on the fly in the view, from a more re-usable IEnumerable list in my model, which means my model doesn't have anything related to SelectLists, SelectListItems or anything MVC specific.
Example as promised - create the SelectList in the view, using all the normal view engine bits...
<%= Html.ListBox("SelectedStuff",
new SelectList(Model.SomeOptions, "id", "name", Model.SelectedStuff)) %>
does this violate MVC patterns when we start adding IEnumerable to our model classes?
Not really BUT if your trying to use a Domain Driven Design or separation of concerns between you business layer and MVC/presentation layer than it is a violation.
Models are your entities, your domain, your business layer objects.
ViewModels are your screens, form postings, display data buckets.
Models map to ViewModels which can contain MVC dependent items. Think if it this way, ViewModels are directly for MVC. Models could be for a service, winform, WPF or any programmatic presentation of the business sytem system.
No, ViewModels are meant to be consumed by the View and should be located in your web project. However, your actual Model should have no reference to MVC or your web project. Think of your ViewModel as bridging that web gap from your Model to your View.
精彩评论