Best practices with ASP.NET MVC view models - asp.net

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/

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.

ASP.NET MVC managing ViewModels

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.

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!

In the Presentation Model pattern can view specific logic reside in the view?

I'm currently using RobotLegs with the Presentation Model pattern to develop a Flex 4 project. I understand that all business logic related to a View resides in the Presentation Model associated with that view, however, I am confused when it comes to View specific logic.
For example, I have an indicator that needs to be positioned relatively to list items depending on which list item is selected. Is it acceptable in the Presentation pattern to put the logic that will position the indicator in the View and simply have that logic run in reaction to a selectedIndex property changing in the presentation model?
The reason I am considering this is that since the Presentation Model does not have a reference to the view it is difficult to come up with an ideal solution for manipulating view components.
Ask yourself this: if you had to use the same Presentation Model with a view that looked different (for instance, a mobile View), would you still need to handle this, and could you abstract it enough to handle it the same way from the PM?
It sounds to me like you're moving the indicator relative to the itemRenderer, which suggests that you may want to have some sort of reference to the renderer or its coordinates in the PM (var indicatorIsRelativeTo:InteractiveObject or var indicatorIsRelativeTo:Rect). You may even want to have another variable that describes how it is relative to that object (above, below, left, right).

Best practices concerning view model and model updates with a subset of the fields

By picking MVC for developing our new site, I find myself in the midst of "best practices" being developed around me in apparent real time. Two weeks ago, NerdDinner was my guide but with the development of MVC 2, even it seems outdated. It's an thrilling experience and I feel privileged to be in close contact with intelligent programmers daily.
Right now I've stumbled upon an issue I can't seem to get a straight answer on - from all the blogs anyway - and I'd like to get some insight from the community. It's about Editing (read: Edit action). The bulk of material out there, tutorials and blogs, deal with creating and view the model. So while this question may not spell out a question, I hope to get some discussion going, contributing to my decision about the path of development I'm to take.
My model represents a user with several fields like name, address and email. All the names, in fact, on field each for first name, last name and middle name. The Details view displays all these fields but you can change only one set of fields at a time, for instance, your names. The user expands a form while the other fields are still visible above and below. So the form that is posted back contains a subset of the fields representing the model.
While this is appealing to us and our layout concerns, for various reasons, it is to be shunned by serious MVC-developers. I've been reading about some patterns and best practices and it seems that this is not in key with the paradigm of viewmodel == view. Or have I got it wrong?
Anyway, NerdDinner dictates using FormCollection och UpdateModel. All the null fields are happily ignored. Since then, the MVC-community has abandoned this approach to such a degree that a bug in MVC 2 was not discovered. UpdateModel does not work without a complete model in your formcollection.
The view model pattern receiving most praise seems to be Dedicated view model that contains a custom view model entity and is the only one that my design issue could be made compatible with. It entails a tedious amount of mapping, albeit lightened by the use of AutoMapper and the ideas of Jimmy Bogard, that may or may not be worthwhile. He also proposes a 1:1 relationship between view and view model.
In keeping with these design paradigms, I am to create a view and associated view for each of my expanding sets of fields. The view models would each be nearly identical, differing only in the fields which are read-only, the views also containing much repeated markup. This seems absurd to me. In future I may want to be able to display two, more or all sets of fields open simultaneously.
I will most attentively read the discussion I hope to spark. Many thanks in advance.
I am doing it like this (the mapping is done automatically inside modelBuilder with the ValueInjecter):
I have a sample asp.net-mvc application where I demonstrate the best practices of doing this in mvc, you can see it in the download of the valueinjecter
public ActionResult Edit(long id)
{
return View(modelBuilder.BuildModel(personService.Get(id)));
}
[HttpPost]
public ActionResult Edit(PersonViewModel model)
{
if (!ModelState.IsValid)
return View(modelBuilder.RebuildModel(model));
personService.Save(modelBuilder.BuildEntity(model));
return RedirectToAction("Index");
}
a quick demo of the ValueInjecter:
//build viewmodel
personViewModel.InjectFrom(person)
.InjectFrom<CountryToLookup>(person);
//build entity
person.InjectFrom(personViewModel)
.InjectFrom<LookupToCountry>(personViewModel);
There have been a few posts recently around the issue of validating your models, resulting in this post from Brad Wilson "Input Validation vs. Model Validation in ASP.NET MVC".
The initial issue was to do with how ASP.NET MVC handled validating a posted model, and if there were elements of your model that you didn't want edited and didn't supply fields for in the view, but your controllers were working with the whole model, it's possible that someone could craft a POST to your controller with the additional fields.
Therefore using a View specific Model enables you to ensure that only the fields you want edited can be edited.
I have the exact same problem, but I wouldn't be able to formulate it that well.
In my case, there would be tons of ViewModels, because different users would see different forms based on a set of roles. I think the 1:1 relation between ViewModel and View is very vague. What if I write an uber-View which pretty much simply uses EditorForModel and not much more? Now I have one, albeit highly degenerate, view for everything, so I also have only one ViewModel?
My idea was to write an EditorForModel that works not only based on reflection (that is, information known at compile time), but also on (domain specific) runtime rules, for example governed by the current user's role, the current time, etc. Consequently, one also needs to write a custom ModelBinder with validation as well as a custom mapping from Model to ViewModel. Still, this keeps me from writing stupid and thus error-prone code.
Since my Model (or DomainModel) contains a lot of logic, I don't want it to be modified via ModelBinding at all. Moreover, since it is impossible to know what fields will be present at compile time, providing an appropriate ViewModel is impossible. However, the 'full', i.e. maximal ViewModel is known. Mapping from the ViewModel to the Model again involves custom code, but as long as the rules can be formalized, that should work out.
Sorry my text is very confusing, but I am very confused right now myself, plus I gotta run. Like C.T., couldn't comment either.
Check this out. This is the way to go with ASP.NET MVC 2.
public void Update(MyModel model)
{
var myModelObject = MyRepository.GetInstance(model.Id);
if(myModelObject != null)
{
ModelCopier.CopyModel(model, myModelObject);
}
MyRepository.Save(myModelObject);
}
ModelCopier.CopyModel(obj from, obj to) is a new function in the latest MvcFutures. Also be sure to check out the Extensible Model Binder in MVC Futures 2.

Resources