Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does using ViewModels and references to System.Web.Mvc violate the MVC pattern?

I've seen it all over SO, blogs, and books, 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.

like image 275
mirezus Avatar asked Jul 29 '10 13:07

mirezus


3 Answers

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)) %>
like image 65
Fenton Avatar answered Sep 18 '22 00:09

Fenton


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.

like image 44
John Farrell Avatar answered Sep 18 '22 00:09

John Farrell


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.

like image 29
dotjoe Avatar answered Sep 20 '22 00:09

dotjoe