Does using ViewModels and references to System.Web.Mvc violate the MVC pattern? - asp.net-mvc

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.

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.

Related

Mapping Domain Models to View Models

I'm starting from a point very similar to: Domain Entities, DTO, and View Models.
The advised use of DTOs to map between the domain model and the MVC's ViewModel seems consistent expectations. I seek details of how to bridge the domain model (Entity Framework-based project) to the WebAPI mvc project.
I'm starting with a project of simple POCOs (generated by EF PowerTools to reverse engineer my existent db) that I want to connect to an MVC4 WebAPI project.
I expect I'll be adding business logic to the baseline POCO project as my solution evolves and perhaps this is the crux of this issue. The business logic that transforms the POCOs into something that can be mapped to the MVC project.
Exactly how do I wire these projects together so i can start creating controllers in the MVC project that knows about the entities of the EF project? Automapper? Can we point to posts/docs where this specific feature of Automapper is employed?
You don't want controllers that knows about the EF entities - that's the whole point of this. :)
You yourself say that the DTOs should be used to map your domain to your view model, and then you ask "how can I bridge my domain model with the mvc controllers?". You've already answered this - with DTOs!
The DTO serves as a transport layer between complex business objects and models used to display a certain view. Both of these have special requirements that don't strictly relate to "just data" - hence using DTOs will give you a greater decoupling and separation of concerns.
If you don't decouple domain from view model, you will be forced to directly reference your EF objects in your view model code, which exposes unnecessary data and functions "up the chain".
Now, if you use WebAPI as a way to ship data then I think you could usually get away with sending the DTOs, since WebAPI data usually wouldn't be implementing view model logic. But YMMV of course, depending on how you plan to use your controllers.
For AutoMapper I'd say it's best to start with their own docs (they even use DTO examples in them): http://github.com/AutoMapper/AutoMapper/wiki/Getting-started

Confused about .net MVC View Models and Models

So, I've read a bit about .net and MVC. I remember reading something that suggested using ViewModels in MVC. This would help lessen the desire to have the view messing with data that should be controlled by the controller.
I thought this is what is referred to by the MVVM pattern. Evidently after looking at that, the implementation actually does away with controllers altogether. Not exactly what I want to do.
Is it still legit to use a ViewModel in my case? Is it better practice or just unnecessary work? Where would you put your ViewModels directory/namespace at? Under the Models directory?
Is it legit for Models to know about ViewModels? For example, you have a Model Return a ViewModel to the controller?
ViewModels are not by default in MVC projects. It is something you need to add if you feel it benefits you to couple View to a Model "easier"
http://rachelappel.com/use-viewmodels-to-manage-data-amp-organize-code-in-asp.net-mvc-applications
The concept of the ViewModel isn't just for ASP.NET MVC, as you'll see references to ViewModels throughout the web in articles and blog posts about the MVC, MVP, and MVVM patterns. Those posts and articles can center around any number of technologies such as ASP.NET, Silverlight, WPF, or MVC... This post will investigate ViewModels as they apply to the world of ASP.NET MVC.
http://msdn.microsoft.com/en-us/magazine/ff798279.aspx
Models and ViewModels are different. Don't confuse the ViewModel with the MVVM pattern.
The use of a view model can make the interaction between model and view more simple. A model can sometimes be over complicated having other model objects as members, which could have model objects as member etc..
By using a view model you have a good way to simplify what the view deals with. This will also filter down what can be seen in intellisense, so if you have different people developing the models than those working on the views, creating a simple view model can make it much easier for those just dealing with the UI.
Design patterns in my opinion are not rigid concepts, but rather guidelines that help you architect your application better. The Model-View-ViewModel(MVVM) design pattern stems from WPF, where there is a very robust Bata Binding framework that facilitated the pattern. The idea is that you have business data in your model, but since there are often view specific data(i.e the currently selected item in a tree control) that didn't belong in the model, you created view model objects that wraps your model, but the view models also contained view specific state data. So your views can bind to the view models instead of the model objects directly, thus keeping the models clean(easy to test, maintain etc).
Asp.net MVC is different in that the databinding in the Views is nowhere near as powerful as it is in WPF. In WPF you could actually implement much of your GUI and model data interaction through databinding, which made the view models useful. But in Asp.net MVC your controllers are designed to handle this, and since the databinding is close to non existant I just don't see the value of having view model wrappers around your model objects in Asp.net MVC.

Generating view with scaffolding for ASP.NET MVC3

I'm doing a project with ASP.NET MVC3 and Linq to Entity . I have separated my data access layer through a different project and of course its not highly coupled with Model.
I have seen the scaffolding ( auto code generation for controller and corresponding views) feature which depends on Model.
Is there any tools or specific procedure through which I will be able to generate views for a specific controller like scaffolding do for ASP.NET MVC without involving model highly like MVC do ?
Thanks
You can go through the MVC Scaffolding articles. Basically what you have to do is edit the default templates and power shell scripts.
The model that you are talking about here doesn't have to be a Database generated class. It can be anything, so what I would do is create a ViewModel (class) that will represent that view you want to display and use the Scaffolding functionality on that ViewModel.
You can then use something like an Automapper to bind your models to the view models

Working with MVC 2.0 and the Model in a separate assembly

I'm new to MVC and even though there is a lot (and I do mean a lot) of information out there that is very useful - it's proofing very difficult to get a clear understanding on how to achieve my exact requirements with MVC 2.0.
I would like to set up a solution as follows:
Provide a web UI using an MVC 2.0 project.
Use Linq to SQL classes project for data persistence.
I have a two separate code modules that will need to access the above Linq to SQL model - so I won't be able to include my Linq to SQL model directly in the MVC project itself.
Also I have a Business Logic layer in front of my Linq to SQL project.
My questions are:
How do I set up the Model part of my MVC application to point to my Linq to SQL project via my BLL?
How do I perform web app validation? Can I use MVC 2.0 Model Validation? If not what are the alternatives?
Finally (and slightly aside) - What is the ViewModel and how does this differ from the Model?
So many questions. But this is an exciting new technology and data access issues aside, everything else I've got to grips with very quickly and I think MVC 2.0 is fantastic.
Thanks for any pointers you can provide.
How do I set up the Model part of my
MVC application to point to my Linq to
SQL project via my BLL?
Typically you'd use a repository pattern for this. Your controller has a reference to your repository - the repository returns your domain objects from your database. The MVC app has no knowledge LINQ to SQL exists.
How do I perform web app validation?
Can I use MVC 2.0 Model Validation? If
not what are the alternatives?
Put view models in your MVC project. These view models may closely align with your domain models but their concern is to be the presentation model. Put your data annotations for validation on these view models - the MVC framework will automatically ensure validation occurs on these view models decorated with data annotations. It's pluggable so you could use alternatives - but with MVC 2, it's baked in fairly well and this includes client side validation.
Finally (and slightly aside) - What is
the ViewModel and how does this differ
from the Model?
I partially answered this one above. the shape of your domain models may not be the shape you need to display your views - view models are great to bridge this gap. Additionally, even if the shape does match exactly - view models are still a good idea so that you can put UI validation code there and other presentation meta-data on them (since you do not want anything related to presentation logic on your domain model).
Here's link for view model patterns.
Hope this helps.
You can add a reference to the objects exposed from your BLL assembly and use them as your Models.
When you want to add validation to classes that are generated use buddy classes.
A ViewModel is a custom-shaped aggregate of Model data. There is exactly one per View, as the ViewModel's purpose is to surface exactly the data needed by a particular View in a convenient and concise way.
An example might be a View that contains both Order and OrderDetail information. A ViewModel can hold internal references to the repositories and business objects for each type. Properties of the ViewModel merge together the data from these objects.
ViewModels will be useful in your case also because you want your Models to be in a separate assembly. You can apply the DataAnnotations to ViewModel properties for validation. You would make the "raw" business object models internal properties of your ViewModels, and expose public methods to retrieve and persist data.

Best practices regarding locations for ASP.NET MVC models

Are there any best practices that cover the places that ASP.NET MVC models should be defined?
A new ASP.NET MVC project has a nice neat Models folder for them to go in, but in a production environment they can come from other places:
Third party class libraries
WCF services
Is it acceptable for a strongly-typed view to use a class defined in such a location?
In just about every project I have worked on the models of ASP.NET MVC are more View Models than models in the traditional sense of the word. I have yet to have a project where I can use the same Model that I use in my data access for my View Model. There is just too much other information that needs to be displayed on most pages. So for that reason I will either store my models in the models folder or store them in a separate library with all of my other MVC specific classes.
I don't know what you exactly mean by putting models in WCF services. If you mean using WCF services that expose the model object you need, that would work.
Regarding separate class libraries to hold your models, views and controllers, I think that's a pretty common approach and works pretty well. In fact, I believe this is really a requirement when the size and complexity of your application grows. It's a kind of physical separation of the distinct logical components in an MVC app.
One issue that I've found is that, unless the model is defined in the web project, VisualStudio seems unable to find it when using a strongly-typed view specified in markup. My models are usually defined in a separate project and I've found that to use strongly-typed views, I need to create a codebehind so that I have a class that derives from a strongly-typed ViewPage. Then I change the markup and associate it with this class.
You need to import the namespace to the view page. This does not require a codebehind page.
Use the directive
<%# import namespace='your.namespace.here' %>
immediately after the <# Page..... directive

Resources