Confused about .net MVC View Models and Models - asp.net-mvc

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.

Related

Is the DataContext part of Model in MVC or a part of Controller?

working on asp.net MVC from quite some time now
today stuck on a theoretical problem
going through some sample code on MSDN
I read something like this
public class SomeController()
{
public ActionResult SomeAction(SomeModel model)
{
var dataContext = new SomeDataContext();
//basic CRUD operations on data context
//
}
}
here the database obviously is being accessed through the controller and by theory is incorrect
is there something wrong with this example or my definition of what a model and what a controller is needs to be refreshed
UPDATE:-
or there is a possibility that every where on MSDN Models and ViewModels are considered equal
intro
MVC design pattern is quite old. It was originally defined for Smalltalk-80 applications, when "web" was two guys sending ping between universities. Since then it has evolved quite a lot.
The core principle behind MVC design pattern is Separation of Concerns. The pattern separates presentation from business logic. Presentation layer contains mostly views, controller, templates, viewmodels and presenters (depending on which flavor of MVC-inspired patterns you use), while business logic is ends in the model layer.
The model layer, while not strictly defines in the pattern, in ASP.NET MVC consists of services and all the structures that are used by service (including the Model Objects, better known as domain objects).
regarding the question
It is quite common to see DataContext uses in controllers, when you are looking for basic MVC tutorials. MVC architecture is meant of large scale applications, and in a Hello-World example a fully realized MVC architecture would look like just bloat.
The examples sacrifice code separation for sake of simplicity. The interaction with DataContext is basically storage logic, which is one of tasks that model layer handles. When used in controller, it means that your model layer has begun leaking in the presentation layer, and you end up with "Fat controller, skinny model" problem.
In a real world application the DataContext would be part of structure that deal with persistence within model layer. Probably as part of data mappers, if you opt to write them manually.
regarding "update"
The model (I suppose in this case you meant Domain/Model object) is from completely different application layer then ViewModel.
As the name implies, in MVVM pattern the ViewModels replace the Controllers. ViewModel acquired data from model layer, and then transforms it in such a way that is usable for View.
This pattern is best used (if you are really using MVVM) in situation when you do not have full control over behavior over Views or/and Model layer. For example: if you were hired to build an alternative frontend for SAP or when the view is actually some form of hardware device, which expects specific type of input.
The Models are typically the data classes (representing the database tables). The View Models are typically referred to as classes that have been created in order to use them in the view for presentation purposes.
You wouldn't be able to use the DataContext on a View Model in the above case, but you can use it perfectly fine with the above mentioned Model classes (also called DTO classes).
MVC is a GUI pattern, just like MVP or MVVM, it has nothing to do with data access and persistence. It's true that many simple CRUD applications are not much more that MVC and an underlying database, but in more complex applications MVC would be part of the presentation layer.
The DataContext as an O/RM belongs to the infrastructure layer, not the GUI. In MVC the Model can be understood as ViewModel, yes.
Nevertheless the controller can use the DataContext or any other means to retrieve this model from the underlying data store.

Why should I use view models?

I'm new to developing web apps using ASP.NET MVC. In fact, I'm rather new to developing web apps, regardless of technology.
Currently, I'm working on a project just to get to know the ASP.NET MVC framework better. When reading on SO and elsewhere on the internet, the consensus seems to be that the views should never deal directly with the business objects (i.e. objects implementing business logic and containing associated attributes). Instead, view models should be used. However, this introduces a couple of issues:
Where do I put my validation code?
I need to add code to map between business objects and view models.
In fact, it seems rather cumbersome and I haven't really seen anyone explaining properly why it's a bad idea passing business objects to the views. Could someone please try to explain this (or point to a good explanation)?
Just a clarification; I'm not looking for examples on how to handle the two issues with view models above but simply an explanation on why I should use view models at all.
Where do I put my validation code?
On the view models you should validate everything that's specific to the application like for example the date should be in en-US format culture, ....
I need to add code to map between business objects and view models.
That's why there are tools such as AutoMapper.
Different problems arise when you use directly your domain models in the views:
The views have specific requirements for displaying the data (localization/globalization) so you either end up with spaghetti code in your views or you put this code on your models so that they become less reusable in other applications because you have polluted them with specific presentation stuff
You have different validation requirements based on the view. Let's take for example the case of Add and Update views. In the Add view the Id property won't be needed and it won't be required because you will be inserting a new item. In the Update view the Id property would be required because you would be updating an existing item. It would be difficult to handle those specific validation rules without view models.
The models might contain properties such as IsAdmin and then I am leaving to your imagination the implication of a controller action with the following signature:
[HttpPost]
public ActionResult CreateUser(BusinessObjectUser user) { ... }
assuming that you have hidden this property from the underlying form by not including it.
The business models don't change often whereas the UI could change more often. What if your customer asks you to split your screen in two? The way you present the information changes and the way it is formatted also change. If you use your models directly into the views the spaghetiness of your views becomes worse and worse with every change.
About 60% of the question I am answering on StackOverflow in the asp.net-mvc tag wouldn't have been asked if the OP have used a view model.
Three reasons to why you should use View Models:
Reason 1: Remove logic from your Views
Reason two: Security
Reason three: Loose coupling
Below link may useful:
http://www.codeproject.com/Articles/223547/Three-reasons-to-why-you-should-use-view-models
First off, allowing the Views to have direct access to the Business Objects in ASP.NET MVC introduces some extra security concerns. ASP.NET MVC does a lot of Model binding for you when a user posts a value back to your controller. This can open you up to various kinds of attacks. By introducing a View Model in between, you can be sure that only the fields you are interesting are bound (because the ViewModel will only contain the fields you care about).
As for the other questions:
Where do I put my validation code?
I use DataAnnotations on my ViewModels directly. That allows me to use the Model validation architecture built in to ASP.NET MVC. If there's any validation beyond that I handle it in my controller.
I need to add code to map between
business objects and view models.
True. But using something like AutoMapper can greatly reduce the amount of boilerplate code that you have to write by hand.
MVC is easy to understand and has very little overhead. But those that have used the Model-View-Controller pattern for some time know that it isn't perfect. Not even close. The Model-View-ViewModel pattern offers an interesting alternative.
It is important to understand that the Model-View-ViewModel pattern extends the Model-View-Controller pattern. It isn't a dramatic paradigm shift if you are used to MVC. Even though the advantages of MVVM are subtle, they are profound.
What are some of the advantages MVVM has over MVC?
Better Separation of Concerns
Improved Testability
Transparent Communication

What's the design pattern name for using domain models & view models (aka AutoMapper) with MVC

Is there a name for the software design pattern that involves MVC with domain models and view models? It's the pattern used when a tool like AutoMapper is employed.
I was attempting to explain the advantages of such a design to some fellow programmers and was calling it MVVM but I'm now of the opinion that's not right and the MVVM pattern is where the view stage is refining the model for its own purposes rather than changing what's passed between the Controller and the View.
Of course it all gets confusing with the number of M's and V's and rather than getting tied up in more knots I thought I'd ask the experts.
Its called MVC. No, seriously. Your website's models just happen to be called ViewModels.
MVC doesn't say what the model is supposed to be, just how its supposed to interact with M and C.
As you might have read or experienced that Automapper is used to map objects. When it comes to MVC, the V (View) and C (Controller) are pretty clear. What confuses many people is the M (Model). MVC doesn't lay strong emphasis on how model should be contructed. You can construct your models by running a direct SQL query or using an ORM tool like NHibernate or LINQ2SQL or Entity Framework of your choice.
If you really want to separate the concerns you can go a step ahead and do what most people do. You can introduce repository pattern to handle model data which can be retrieved using a service. This is the situation where Automapper would come into the picture where you need to map entities and Dto's.
I don't think there is any need to abbriviate this method of building models from service layer. The normal MVC stands valid in this case as well :)
The "Related" questions provided me with the best answer I think I'm going to get.
The design pattern is defined fairly well in the article How we do MVC – View models and the appropriate monica seems to be MVC-ViewModels or MVC-VM.

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.
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.

ASP.Net MVC and N-Tier

Greetings,
Apologies in advance that I have not researched this toughly enough to answer the question myself, but I imagine it would take me some time and I would rather know now before I invest more time in learning it. I couldn't find anything in my initial research..
Why use ASP.Net MVC if your already using a multi-tier architecture (Data Layer, Logic Layer, Presentation Layer)? Other than the fact the controller has more power than the logic layer.
Am I right in thinking I can use nHibernate and all my data access classes, entities, and mappings in the Model part of the MVC?
When using controllers, is it best to separate a lot of the logic into a separate class so I can call it from multiple controllers? Or can I call them from the controllers themselves, considering the fact that I would not want all of them to be Actions, just normal methods.
Thanks
MVC is not to replace N-Tier, it is a way to organize the presentation layer.
I would not say that the controller is more powerful than the logic layer. Instead, the controller (as a part of the presentation layer) should still call the logic layer.
Controllers should only prepare data for views and handle actions from views. You should still use your BLL.
Yes, NHibernate entities can (and they should be) be passed to the views.
This will you get you into some trouble. You should use flattened, null-safe DTOs a.k.a. view models.
Damien, you might want to read these 2 posts:
The Fat Controller
An Architectural View of the ASP.NET MVC Framework
N-tier is an archtitectual pattern, to enable reuse, seperaation of concerns and scalability of the key areas of your application.
The non UI layers (Business, Data, Facade etc.) should be unit tested and UI agnostic.
The UI layer is just one of these layers weather it be Silverlight, ASP.NET MVC, web forms etc.
MVC, like MVP is a design pattern that enables better testability of the UI Layer.
ASP.Net MVC is an out of the box framework that supports and enforces this pattern.
The pattern was arround an in use long before this framework.
But this is simply a UI layer choice, There should be no interaction with databases, services etc in the controllers, they control the state of the view using the model, Should not control the business logic, peresistence, transactions etc.
To answer your question on why use if you are already going multi-tier is that it makes for more organized and search-engine friendly URL's. Also, it is more of a standard pattern than the other patterns tend to be in ASP.Net. That makes it more developer friendly for those that are already using MVC on other platforms.

Resources