ASP.NET MVC managing ViewModels - asp.net

In our ASP.NET MVC 3 application, we displays a lot of information from various data sources as listed below
Action method parameters
Query string (which can not be used in model binding)
Session
WCF Service
Database
We have to combine the data from all above stated data sources, format and dispay it in a view.
How to divide the classes so that it will have better maintenability?
If we use view models, how to construct the view model by combining all information?
Where to Keep the mapping between Domain Model and View Model and vice Versa?

How to divide the classes so that it will have better maintenability?
By defining view models that will be specifically tailored for the requirements of your views.
If we use view models, how to construct view model by combining all information?
You could define a view model that will contain all the necessary information you need to display in a given view. If there are shared widgets between your views you could have child view models that the main view model could reference as properties (composition). The child view models could then be reused in other contexts.

Related

Why use ViewBag instead of Application["x"] in View?

I see references to "best practice", but why is it better to use a ViewBag object versus an Application object when accessing static data in the view?
Both are possible. Suppose you want to add an object to every view but not necessarily pass it to view the model (since there may not even be a model for a given view)?
This could be done several ways, like with a global filter, but accessing an application variable is much more convenient.
Both are nasty workarounds that bypass everything that MVC stands for.
In the Model-View-Controller pattern, your Controller prepares a Model containing all values necessary to populate the View, and the View in turn displays the Model properties the way it's intended to.
Any way you use to circumvent that pattern, like ViewBag, Session or Application variables, are anti-patterns that defeat the MVC way - as long as you access those variables directly from the View.
See also Pass data to layout that are common to all pages and Create ViewModel for Navigation: if you need certain values on all pages, consider using a base viewmodel or partial views.
And yes, this discussion borders on pragmatic/purist. If you for example have a menu that's the same for every user, but which is loaded from a database, then sure, go ahead and store it in an Application variable for caching purposes to load it once per AppDomain. But then still use a base ViewModel or Partial to render that menu.
I wouldn't say putting data in a view bag is a best practice. I would say using a view model is a best practice.
Suppose you want to add object to every view but not necessarily pass
it to view the model (since there may not even be a model for a given
view).
Even if you haven't define a view model, conceptually there is a model is you are passing data to the view.
See Why do we use ViewModels?
If the data is on every view, you could create a base view model that every model inherits from that contains the universal data.
you could also create a partial view with its own view model that is then applied to each page.
Normally I design ViewModels taking in consideration the business or functional concepts of the application.
For example, if you are displaying an invoice, the view model should contain all the properties related to invoices that needs to be displayed on that specific view. I wouldn't use ViewBags/ViewData for this purposes.
On the ViewBag I normally put other and "more ancillary" properties like, for example, a boolean for showing/hiding some part of the view, or maybe for some other "not business relevant" properties.
Of course some people could disagree with this and would put everything on the Viewmodels, some others not. This is a decision you must take at the beginning so you can be consistent in the way you design across the application.

Is it common to use POCOs and model binding to do contextual validation?

I've noticed in ASP.NET MVC, it's commonplace to use model binding and validation annotations in conjunction with business objects that also interact with the database.
Unfortunately, this means that the scope of the request and the validation taking place must always be 1:1 with domain models. At the very least not without having to code a bunch of exceptions.
If I'm looking for a way to do contextual validation in ASP.NET MVC, are there any examples of or is it an accepted practice already to use POCO classes that represent the incoming data?
Let's say I call these "Request Models". An example might be that I create a class called UpdateUserRequestModel. I define only the data that I allow for a user update, then, I have MVC bind the values into this surrogate model. Later in my controller/services, I access the request model's public properties for the values I wish to move over to the user object.
So, the question here is: Is there already any example of this practice in commonly accepted ASP.NET MVC conventions? Does it have a particular name? Failing that, when I wish to do contextual validation, are there any better options than the default model binders and value providers that MVC ships with?
I do it on my apps. I validate actions the user performs, putting validation attributes etc on that view model that represents that action (conveniently models the form in the view and model binds the result on the way back). I even ported the ContosoUniversity app to reflect this style:
https://github.com/jbogard/ContosoUniversity

What's the key difference between a ViewModel and a Model in ASP.NET MVC?

What requirements should each of these meet to be classed as either a Model or a ViewModel? (Aside from the directory they live in)
Thanks all,
Dave
Although Oded is correct in ViewModel not being part of MVC, many people still use that terminology to describe a model that is essentially one or a combination of translated data classes for presentation purposes.
In a typical implementation, the MVC Web project may not be able to have direct access to the DTO classes, it in turn calls a method in the Core layer which calls the database, retrieves the DTO objects and translates them into a "View Model".
I suppose it helps newcomers (who refer to their data classes as Models) distinguish between the DTO classes and classes built purely for presentation purposes based on the DTO classes.
A ViewModel is not part of the MVC pattern, to begin with.
It is part of MVVM.
The MV in both pattern mean Model (as in business/domain model) and View for the UI.
MVC also has a Controller, which is the orchestrator between the view and the model. In terms of the defaults of the Microsoft MVC framework, the Controllers, Views and Models each go into the directory of the matching name.
MVVM has the ViewModel which is a model of the view itself. Since this is not part of the MVC pattern, there is no place for these by default in the MVC templates by Microsoft, though if you wish to introduce this abstraction, you should create a ViewModels directory for them.

ASP.NET MVC3 - Multiple Stored procedures on Single Page

Is it possible to call multiple stored procedures (not multiple result sets from a procedure) and display results on a single page in ASP.NET MVC 3 application?
From what I understand only one Model can created on any single page and my stored procedure is already tied to that Model. I would like to call another procedure and display that result as well on my page
I think the root problem is to understand the meaning of the Model in the MVC pattern.
First of all,
The model consists of application data and business rules, and the controller mediates input, converting it to commands for the model or view.[3] A view can be any output representation of data, such as a chart or a diagram
source
In ASP.Net MVC you link a model to your view, this model should not be part of your domain logic or any domain object
The real model (using the meaning of the MVC pattern) is represented by your domain objects.
So what should you put inside the object that you link to your view??
These objects should contain a representation of the view, in other words simple DTO's containing only the data that is going to be used in the view and nothing more. These models should represent the data being used in the view. If you follow this approach, and you need to display more data in the page, you only need to add another property to this model and voila, you can use it from your view.
In a CQRS architecture, these DTO's should be populated by the Query repositories.
If you do not have a CQRS architecture, just populate these objects in your domain, repositories, etc. Do not do it inside the controller, keep your controllers clean and simple, by making calls to your real domain using services or repositories
Try to avoid the reuse of these DTO's, they should belong to one view only. And do yourself a favor and do not try to reuse a domain object instead of a DTO just to use it as the model.
Following this approach your view-models will be clean, since they will be only DTO's and only containing the data needed by the view. And you can fill these DTO's from different sources, even from different databases if you want.
When you want to perform an action you would read from the model the data provided by the user, and with this data you would call your domain through repositories, services or in a CQRS arc. using commands
The simple answer to your question is "yes".
I suggest you do some more research (ie reading articles and looking at sample apps) into MVC and concentrate on understanding these points:
The Model is a class used to group the data you want to display in the View. It can be populated by a variety of methods and does not have to be the domain object or the pure representation of the database result.
A "page" (the concept of what a user sees in their browser window) can be made up from one or more Views. Each View can be responsible for displaying one type of Model allowing for reuse, but a "page" can have multiple Views.
Models are not "tied" to stored procedures. Perhaps you are using an ORM tool that returns a DTO class (which you call model)? This doesn't have to be the Model used by the View. The Controller could compose several of these DTO classes into one Model class.
N-tier application design where database access is separated from the display logic. MVC tries to encourage this but it still has to be done correctly to avoid tying yourself in knots.
Good luck!

Best practices with ASP.NET MVC view models

I ask myself how do I create a view model correctly.
For instance, I have an edit view with some text boxes and a dropdownlist.
Should I separate the dropdown list into a new view model or shoud the edit view have one viewmodel with a list for the dropdownlist?
Or generally speaking, should I separate special input fields in separate view models?
When should a view have more than one view model and when not?
There's no clear rule of how to create and organize your view models correctly. Your question is too vague to be answered because you provided too little context.
I usually group view models according to functional blocks/parts of the screen they represent. So for example imagine that you have a complex form composed of multiple sections/fieldsets like contact details, delivery address, billing information, etc... An address could be composed of street, zip, city and country dropdown. I would create an address view model containing those four properties so that it can be reused in multiple views/partial views. This will also make validation easier as dependent properties will be packed into the same view model like validate for example that the given zip corresponds to the city and that the city belongs to the selected country.
For instance, I have an edit view with
some text boxes and a dropdownlist.
Should I separate the dropdown list
into a new view model or shoud the
edit view have one viewmodel with a
list for the dropdownlist?
I would say no, if those fields are somehow functionally related.
Conclusion: you will have to find the right balance between having a view model per field on the screen and having a single view model per application.
I prefer the approach of one view model per view/partial view. This is in my opinion the best approach if you believe the view model's single purpose should be modeling the view. This paradigm also supports the use of strongly typed views thus providing compile time error checking for your views model binding and you get the added benefit of intellisense. In the scenarios where you want to re-use some logic, I find it can often be satisfied by re-factoring the view into partial views and providing these partials with their own view models. It should be emphasized that no domain logic should exists in your view models as it really belongs in a domain model.
You should separate the dropdown list into new view model if you want to be reusable.
You would generally want to use ViewModel pattern if you want to store the data used by the typed view. For UI specific logic and details, a ViewHelper pattern would be more suited.
For some discussion on ViewModel see this article. http://theminimalistdeveloper.com/2010/08/21/why-when-and-how-to-use-typed-views-and-viewmodel-pattern-in-asp-net-mvc/

Resources