Why should I use view models? - asp.net-mvc

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

Related

MVC: Should model inherit from BLL object or containt it?

What pros and cons for:
Use BLL as model.
Model inherit BLL.
Model contain BLL.
Model has only fields that are going to be used by view.
Something else.
Background:
I have some heavy BLL class with about 100 fields. I'm going to show some of them in a view. How a related model should look.
No pros, only cons for all those approaches. The best approach is a combination of 4 and 5. It is called view models. So create a view model for each view which contains only the fields this view needs and map between your model and the view model. This mapping could be facilitated with a tool like AutoMapper.
First, let's make some assumptions clear.
The "ASP.NET MVC" is based upon a proven standard, known as the "Model-View-Controller" architectural pattern. This is not a new invention from some Microsoft geek; quite the opposite, this pattern has been used by several frameworks since 1979.
So, what is "the model"? Using a more modern term, it is the domain logic. It is your business entities, your data access objects, even some of your static declared enumerations and collections: anything that is used by your application, has business value and is not related to some specific presentation issue or requirement.
That's why I said your question, deep inside, does not make much sense.
After you tried to explain what your question is about, and after jim and Darin Dimitrov answers, I guess what you really need, what you are really asking about, became a little clearer: what you want to know is how to bind your existing, pre-MVC business layer with the C and the V of an ASP.NET MVC application.
So, if you do have a well designed BLL layer, and, more importantly, if your BLL and DAL communicate through some DTO's, you could, theoretically, bind them directly to your views.
If those DTO's need to be transformed in some way (because they could not be directly understood by the end user, for instance), this should be done by the use some "ViewModels", which are basically another set of presentation specific DTO's, plus data-annotations for server-side data validation. This transformation, of course, should be done by your controllers.
Some MS people will say that you MUST use viewmodels, and that if you don't use them you will rot in hell. I do not entirely agree. Of course, there are several advantages in using view models (like the already mentioned data-annotations, compile-time verification, intellisense and so forth), but if many other successful MVC frameworks are fine without them, I don't think it should be different with ASP.NET MVC.
That's my 2 cents.
Edit Another important advantage of using viewmodels is related to security: by exposing a set of presentation-only DTOs, the real domain-objects become somewhat protected.
Kamarey,
You can safely use your exisiting BLL (if it satisfies the business needs). You then simply need to identify the discreet sections in your views that you want to update and create ViewModels for those. You may find of course that there are some instances where you can strongly type your exisiting BLL model down to the view. i.e, e.g. etc..
<%# Page Title="" Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IList<yourbll.model>>" %>
In short, i think you'll need to analyse the needs of the views in relation to your BLL.
take a look at this SO question for inspiration on the ViewModel:
ViewModel Best Practices
http://stephenwalther.com/blog/archive/2009/04/13/asp.net-mvc-tip-50-ndash-create-view-models.aspx
http://www.highoncoding.com/Articles/659_Implementing_ViewModel_in_ASP_NET_MVC_Application.aspx
I think the best approach is mostly a combination of 3 and 4, using whichever is easiest for a particular view.
Where the bll object is exactly what the view needs, you can use it directly. This doesn't come up much though, as you almost always need something else - values for a dropdown, names instead of ids, etc.
Where the data object is very close to the view, I have it as a property of the model object. That way my controller can jsut set model.DataObject instead of copying properties individually. On edit forms you need to be careful that your view contains fields for all the data object properties (obviously not a good choice if there are sensitive fields), but it is perfect for read only views.
For more complex views or those that don't really map well to a single data object, use a custom model object and copy the properties you need so you have complete control over what is included and can keep the view code simple.
I have tried using inheritance, but that really just gets you the worst features of all the other approaches.
It's also worth noting that you can quite easily switch to a different model if you need to - with strongly typed views any mismatches are easy to find and fix.

ASP.NET MVC - when SRP and DRY appear to conflict

My simplest ASP.NET MVC 2 controllers make calls to my service layer and map view models to entities using AutoMapper. Everything looks fantastic and there is no repeated code.
However, when I get into scenarios where I have similar behavior I have trouble balancing Single Responsibility Principle (SRP) with Don't Repeat Yourself (DRY). An example of this might be the need to add/edit vehicles where some properties/behaviors are shared while others are unique to a specific vehicle.
If I strive for really thin controllers (thus honoring Single Responsibility Principle), I end up having repeated code in both the views and controllers with minor variations (title, field labels, field visibility, dropdown values, selection criteria, etc.).
If I strive for non-repeated code I end up bundling too much logic into a single controller/view and it gets bloated.
What are some ways of addressing repeated code in controllers / views? I'm not talking about database code that can be factored out to a repository. Nor am I talking about business logic that can be factored out to a service layer. I'm looking for tools and/or rules of thumb that will help me produce the best solution in the scenario described above.
You get:
partials
RenderAction
action filters
service layer and helper classes (not HtmlHelper)
model binders
base controllers
dependency injection
So your views can invoke shared partials/actions for similar parts, common data can be prepared by action filters, database access code can be hidden in smart model binder, or you can have parent controller that child controllers override with specific tweaks. And, of course, good old service layeres, where you just extract common code into helper/static methods, or, better, inject specific implementations.
That's nothing new, same old tricks.
Or, maybe, your controllers do too much works? This is where stuff above also helps. ASP.NET MVC has very good tools to hide infrastructure-layer code and move it away from controllers. And if it's not infrastructure - it probably belongs to domain layer. There you can use inheritance, composition and other OOP tricks.
Specific example. Suppose your controllers should set few properties in a different way.
You can have your views to do this, if it's mostly formatting or choosing what properties to show
You can have your entities to have virtual methods - i.e. refactor code to move decisions to domain layer instead of controllers
You can have helper ViewDetails classes that will take your entities and get the data based on for what you need it; this is a bit of a dirty trick but sometimes useful; you delegate decision to another "strategy" class
You can use action filters to add this data to ViewData, or to tweak specific ViewData.Model types (look for some interface of it).
You can have abstract controller, where children pass implementation details to the base constructor like (): base(repository => repository.GetSpecificData())
And so on. I actually use all of them in appropriate places.
You are worrying too much about SRP and DRY. They are principles only and are not always right. SRP and DRY are good if they make your code more maintainable, but if they are in the way then ignore them. MVC is similar. It is useful in simple small desktop applications but is not appropriate for web applications. Web Forms is much better for the internet world while MVC is something from the 1980s.
I recommend you to use SRP over DRY in those cases. I wrote here a detailed answer.
In short both are rules which help to keep your code maintainable. DRY is a low abstraction level mechanism, while SRP is a high abstraction level. By maintain an application the high abstraction level structure is more important than the low abstraction level.
In your case I don't think it is necessary to give up DRY.
An example of this might be the need to add/edit vehicles where some
properties/behaviors are shared while others are unique to a specific
vehicle.
Many design patterns can help in this case. You can use decorator, composition, and so on... combined with builders for the different types of vehicles.
I found that ApiEndpoints is very good for this. You create a class for each controller method. A little more code, but I think it's very clean.

In MVC (Asp.Net MVC specifically), should a model be represented by a single view?

To me, this seems to make little sense, but after reading the information in the following:
http://weblogs.asp.net/scottgu/archive/2010/02/05/asp-net-mvc-2-release-candidate-2-now-available.aspx
http://bradwilson.typepad.com/blog/2010/01/input-validation-vs-model-validation-in-aspnet-mvc.html
http://blog.stevensanderson.com/2010/02/19/partial-validation-in-aspnet-mvc-2/#comment-35397( specifically some of the comments)
It appears that the idea behind Asp.Net MVC is that you have a one-to-one relationship between models and views. This seems to go against the DRY principle and several other standard programming practices.
For example, lets say you have a user account model and there are two views available to edit it - one for the user himself to edit it and one for the site admin to edit it. The admin has access to an additional field for something internal, required but the user cannot view/edit it. Per the model binding functionality and the beliefs described in the posts referenced above, I would need to create two separate user models, one for each page, and the only difference would be that additional field. This is just a simple example as well, I've got a few that I've seen where it would potentially mean 5 or 6 different models for the exact same object, just a few fields different between each view. That really doesn't make any sense to me.
I did not read the posts you mentioned, but there is nothing wrong with having one Model for a couple of views.
I would just have this one UserModel and use it in all Views, even if there are some fields that are not used.
If things get a bit more complicated but Users still have a lot in common you can either use aggregation for the usermodel (User.Address) or use Interfaces (User has fields street , and city and implements IAddress).
Both methods have their pros and cons - with aggregation used in the majority of situations.
EDIT
After reading the posts I saw that they deal with validation. This is a different story.
If you want to use DataAnotations you have to have different classes if validation varies. I dont use DataAnnotations - so I guess your class design might be different.
If you're using annotations, I'd strongly consider one "model" and multiple "viewmodels." We went with a viewmodel approach on our current app and have been reaping the benefits, because our basic model needs to be shown in a couple different views.
There is no official requirement to have only one view per model in ASP.NET MVC. In many cases that would lead to duplication of code.
I personally like to split model-view dependencies, that is, one view per model. It comes down to the fact that you never know how, say, a couple of very similar model-view pairs are going to evolve in the future. If they're separate, you just introduce changes in one and you don't have to "fix" the other views that were dependent on this model, or worse, to take extra work to create own models for them all at once.
TL;DR: Make many view models. They are cheap and flexible.
"This seems to go against the DRY principle and several other standard programming practices."
[Citation Needed]?
MVC doesn't change the fact that in any language or pattern you need to make a view model definition for each separate screen. Whether via attributes, via XML, via toggling web form controls, whatever.
The DRY principal usually pertains to repeating business logic. Repeating a FirstName property across a CRUD screen section really isn't a big deal. Even 5-6 times, whats that? 40 seconds?
If you mistake your view models for object oriented classes and not homoiconisticish screen representations you run the risk of filling them up will all sorts of inheritance and or business logic.
Your not really programming when you make dumb view definitions. This work could easily be done in an Access GUI or defined in XML. The fact that your screen-view-models are in C# just makes it easier to fill them up with data and ship them around and work with tools like WCF and Automapper.

MVC - Separation of Concerns

I'm a newbie. I want to ask about the MVC model for separation of concerns. I have read up a few MVC tutorials but I don't yet have a full understanding of the roles of each of the Model, View and Controller.
For instance say I am writing an application for a user to monitor a portfolio. I would like the landing page to display lists of investments based of different criteria, for instance one may list investments based on amount invested, another may order it based on investment performance.
My question is, in accordance with the design pattern where should I write logic for generating the lists; in the Model, View or Controller?
Also any asp.net MVC examples demonstrating seperation of concerns is much appreciated.
Thanks in advance guys.
At the risk of repeating myself, I'll point you to the answer I gave in this thread. The entire thread is probably worth your time, as are dozens of others on Stack Overflow.
To break it down simply:
Controllers - control application flow and makes decisions about data.
Models - perform business logic.
Views - produce output.
For your particular situation, you will want to produce your lists in the View layer. Use templates to create your list structure, and fill them with data fetched from the Model layer.
I'm not an asp.net programmer, so I can't give you a reliable example, but have a hunt around for other SO threads.
Nice question, this is subjective and there are many solutions, it comes down to the context I think and the preferences of the individual.
With ASP.Net implementation of MVC alot of people talk about the Model being more of a ViewModel than a Model as in some other frameworks (somewhat of a DTO). This in mind and looking at the Controller as just a coordinator of the flow of the application, it would not be wrong to generate the lists in an additional layer accessed via a service of some type. You would make a request to that service for a set of ViewModels which meet a specified set of criteria and let that extra layer worry about the way in which those lists are generated from that set of criteria. This way all the controller needs to know about is passing some criteria to the service and providing the view with a set of models (viewmodels) to display, the view is free of making any decisions about what to do with the data it has been provided, and the models are nice and lightweight.
Hope this explanation makes sense, and I'm open to criticism if people don't agree...
MVC pattern "requires" you to insert all your "business logic" in the Models. Models are used to access database and fetch data and mold it in a way that you just have to use a Controller to assign it into a View.
An graphical example : http://www.bhartisoftland.com/technologies-skill-sets/gifs/mvc-php.png
Needless to say perhaps, that you can bypass the use of models and write all your logic in the Controllers, but that would result in a very extensive and probably redundant amount of code. Controllers are used so you can call Models and Views, and exchange information from one to another with just a few lines of code.

ASP.Net MVC View Structure

I just finished Scott Gu's Nerd Diner tutorial. I found it very helpful because it not only taught the basics of ASP.Net MVC, but also how to use with Repositories, Validation, Unit testing, Ajax, etc.. Very thourough, but still manageable.
However, I am curious about his site structure:
Specifically, he used this view strucuture for every object:
/ModelObject/Edit/
/ModelObject/Create/
Then extracted the common elements between the two views and put them into a partial.
I understand the logic, but it seems like it would lead to "view explosion" if you have even a moderate number of tables in your database.
Scott's really good, so I am assuming his structure is right. But I would like to know why.
Thanks!
[Edit for clarification]
I realize that many times it is necessary for there to be multiple actions (and views) to handle differences in creates and edits. It is the case of the very simple edit and create, where the only difference between the two actions is in one case the model has an ID and needs to be updated, and in the other case the model does not, so it needs to be inserted.
In this case, is the violation of the "Dumb View" rule by using the same view to handle both cases going to cause major problems?
The view structure is based on the controllers, not the model directly. In the Mvc methodology, you should have a view for each action (each public method, essentially) in a controller. The controller actions don't have to match up directly to each table in database but there is likely some sort of direct relationship between the number of tables in the database and the number of controllers and views. Controllers are higher level
It is standard to have CRUD type actions on the controller, when they are applicable:
Index: list the items
Details: view a specific item
Edit: edit an item
Create: new item
Delete: delete an item
Each of these actions will require a view (and sometimes more than one).
So, yes, you can collect a large number of views if it is a large application. The way to minimize the code is:
Extract shared functionality to partial views, as to keep the action views as small and simple as possible
Keep the views and controllers simple so that they are easy to maintain
Use AJAX to implement more functionality in one view
It's important to point out that any large application is going to have lots of forms. Whether it's Mvc or Web Forms, if there is a lot of data to work with, there are going to be a lot of forms necessary to do it.
It is true that this can indeed lend itself to a lot of views. However, I've found that in my real life applications, I'll have a number of tables that I don't have a 1:1 correlation to CRUD operations. While I certainly have data that goes into those tables, I've found that most times a view presents data from at least two if not three or more tables. Just like every other application, you've got to know what you're after so that you can plan things out. Any large size application is going to require quite a bit of planning up front (which would include analyzing the number of views/controllers for MVC).
It's only the small apps that you can sling together based on you hunches and past experience.
if you have a background as asp.net webforms developer, your answer is natural.
There are several questions, it depends on the point of view. At first, with asp.net-mvc we do not have fully-equiped server controls making many things for us, without a real awareness what they do. Now you have to type more code and have eyes like a surgeon on html.This way I can find a reasonable question for "view explosion"
Other projects follow more or less that structure, see the project by Rob Conery:
Mvc Storefront
PS: "Skinny controllers, Fat Model and… Dumb view"
[Update response to clarification]
Mhh.. I think there's no violation of "dumb view". The important thing is that the all the views has nothing to do with the code in the business logic layer or in your model. You can a have a button "Save", it is the controller has to know which action must be executed, insert or update.
On more reflection, this is what I am thinking:
Combining the edit/create views would be easy on simple models because
- Same properties displayed
- Same validations
BUT doing this would force you to either
- handle both the update and insert in the same action
- use a control statement in the view to determine which view action is used to update
Both options seem ugly and unnecessary when it is so easy to use separate actions and separate views with common code extracted into a partial.

Resources