Best practices/preferences for passing hierarchical data to views? - asp.net-mvc

For simplicity in an example, lets say I have data classes from an object model with the following hierarchy:
Author
Book
Chapters
Each of these data classes only contain references to instances for their children, not their parent, for their parent they only contain the Id. For example, Book has Book.Chapters, but it does not have a reference to its parent (ie: Book.Author), instead it has the Id of the parent (ie: Book.AuthorId).
Now I want to display 'breadcrumbs' for this hierarchy in my view. But to do so, I need to get information such as Author.Name, Book.Name ... So as I see it I have the following options:
Create custom models for each view. ie: new SingleBookViewModel { TheAuthor = DB.GetAuthor(book.AuthorId), TheBook = book }
Get the data in the view itself from the book. So if I have the book view for example, I would be able to use: Author author = GetAuthor(book.AuthorId)... and do this within the razor view itself.
Pass the data in using the Tuple class. So for viewing a chapter I populate the Model with a Tuple with the following signature: Tuple<Author, Book, Chapter>
Which method would you use? Or would you use something different?
Currently I am using the third method, with the Tuple.
The 2nd method is likely the most 'standard'. But I dislike the idea of having to create and maintain view model classes that correspond to each of the data classes (Author, Book, Chapter) behind them.
I'd like to understand what 'best practices' people have put around something such as this... and whether using Tuples makes sense.

I would implement this with ViewModels. Each of your views will be strong typed to a ViewModel that will contain all data needed for that view. You get a collection of Authors in that ViewModel, which contain a collection of books, which contains a collection of Chapters.
As an alternative you can bind your View to a collection of Authors, and upon selection of an author make an ajax get request to a controller's action that returns the books in Json format. The same would apply to the Chapters.

Related

View object having a reference on model object?

I am developing an document based application using MVC pattern, my model object is Mutablearray of mutableDictionaries. Each dictionary in the array is represented to the user by a View object. (for example if the array contain 100 dictionaries then 100 views will be addsubviewed to self.view)
I learned that in MVC pattern the view and model should not know about each other instead they must respond via a Controller object(UIViewController).In my application I followed the MVC pattern but I did not follow the one I mentioned here because by holding a reference to the model object(NSMutableDictionary) I can easily modify the model object(as the user edit the view object) and then write the array of NSMutableDictionaries on the disk after the user finished the document.
Tell me If I should isolate model and view if so what benefit I can avail or I can go on with that

difference between models and view models

I have been researching asp.net MVC project structure's for a new project and have a question about something is confusing me. What is the difference between models and view models? Would I be correct in saying that view models encompass models in the form properties?
I've a blog where I want to display the list of the latest posts, latest comments, post categories in a single view. How I can do that? I can strongly type my view to any one of the model right? There comes view model.
I created a view model called BlogViewModel that contains latest posts, latest comments and other stuff as properties and I bind my view with this model. The posts, comments.. are domain models while the BlogViewModel is the view model I created specially for the view.
Tomorrow I'll show my blog in a mobile version and at that time I may create a simple view model that contains only less properties. Finally.. view models are for views and most of the times they acts as wrappers over the real domain models!
A model is usually more closely related to how your data is stored (database, services, etc.) and the model will closely resemble those.
The ViewModel on the other hand is closely related to how your data is presented to the user. It is usually a flatten version of your model, denormalized, etc. It can be the aggregation of multiple models.
For your typical Person objects, your model may contain properties like the following:
FirstName
LastName
BirthDate
However, in your ViewModel you may choose to represent it differently and have something more like:
FullName
Age
ViewModel is the version of a Model from the business-domain layers adjusted to the specific View.
It has only Properties relevant to the view and shouldn't have methods(except simple ones like ToString()).
ViewModel is a "data container" only.
A model is simply a representation of an object in your application. However, there are a few different types of models that you should be aware of.
Domain Model: This represents a domain object in your application, like a SQL table if you are using an ORM (Linq2SQL, EF).
View Model: This represents an object that you want your end users to view/edit/etc. A view model could contain properties from several or no domain models and typically exclude properties that your end users should not be mucking with. View Models should only contain the elements that are needed to display the appropriate data to the end user for a specific request.
Here is some Jimmy Bogard for you about View Models and their use.

Scope of viewmodels in asp.net MVC 3

I have read online that it is bad practice to use a "kitchen sink" model:
Rule #3 – The View dictates the design of the ViewModel. Only what is
required to render a View is passed in with the ViewModel.
If a Customer object has fifty properties, but one component only
shows their name, then we create a custom ViewModel type with only
those two properties.
Jimmy Bogard's subsequent explanation of how this is good, however, left me a little questioning. It'd be so easy to have my Model just contain a list of Customers, I could even use my POCO's.
So now I get to create custom little view model fragments for every page on the site? Every page that uses a Customer property would get one, but of course could not be shared since some of the information is extraneous, if one page used Age but not Name, for example. Two new mini view model classes right?
This is very time consuming, and seems like it'll lead to a million little custom view models - can someone elaborate as to the utility of this approach and why the easier approach is bad?
View model class can be used not only to transfer values, but it also defines data types (data annotations), validation rules and relations different then ones used in model. Some advantages that come to my mind right now:
There are different validation rules when you change user's password,
change his basic data or his subscription setting. It can be
complicated to define all these rules in one model class. It looks
much better and cleaner when different view models are used.
Using view model can also give you performance advantages. If you
want to display user list, you can define view model with id and name
only and use index to retrieve it from database. If you retrieved
whole objects and pass it to view, you transfer more data from
database than you need to.
You can define display, and editor templates for view models and reuse them on different pages using html helpers. It looks much worse, when you define templates for model POCOs.
If you would use your POCO objects as view models, you would essentially be showing your private objects and break the encapsulation. This in turn would make your model hard to change without altering the corresponding views.
Your data objects may contain details that are appropriate only to the data access layer. If you expose those things to the view, someone might alter those values that you did not expect to be altered and cause bugs.
Many of the same reasons as for having private members in OO languages apply to this reasoning. That being said, it's still very often broken because it's a lot of extra work to create all these "throw-away" models that only gets used once. There exists frameworks for creating these sorts of models, though the name eludes me, that can tie objects together and pick out the interesting properties only which takes away some of the drudgery from creating specific view models.
Your View Model tells the View how data should be shown. It expresses the model. I don't think its necessary to have two view models unless you have two ways to express your model. Just because you have two pages, doesn't mean you will be showing the data any different way, so I wouldn't waste time making two mini View Models when it can be in one reusable view model, Imagine if later you have a page that needs Name and Age, you would create another view model? It's absolutely silly. However, if you had two pages both showing 'Age' and it needed to be shown in a different way, then I would create another one.

How do you elegantly program ASP.NET MVC when the View needs more than one Model?

A View accepts one Model.
But I need to draw HTML input controls for two models.
An example will illustrate:
I have a screen where I add Employees.
After adding their first name, last name and so on, I need the user to choose a number of Companies the Employees could be in.
The Companies are in one table.
The Employees are in another.
And a linking table joins them.
So it seems I need to pass the Companies to the View.
Can I pass multiple models to the view?
Or do I have to do an ugly database lookup in the View to find the Companies and manually spit out HTML for checkboxes without HTML helpers?
A Model doesn't have to consist of just one object or a single collection of one type of object. It can contain many objects and/or collections of objects. It seems that the model required for your page consists of at least collections of both employees and companies. If you have no type which fits this bill in your business object abstraction then you need to create a ViewModel for this page which can do the job.
This answer may help to explain how a ViewModel fits in MVVM ViewModel vs. MVC ViewModel
This is not entirely obvious - I'm sure it is to some guru types but for the rest of us trying to work things out its a bit more interesting.
Without going into detail I see a number of ways of solving this:
You need both sets of data so you need a view specific View Model
Your model is the Employee but you can still add other data to the ViewData - so make the Employee the model and pass the company data in as well as view data but not part of the model
(You may want to do this regardless of what model you use) Render the company selection elements as a separate view - which is where things get interesting - you obviously have to pass the existing selection, or a means to identify same, to the component view but do you have to pass the company list or could you, at this point, cheat a bit (prgamatically)? My feeling is that this is a partial view and that you need to pass it a company selection model (list of companies with selection indicated) but you could in theory do RenderAction and have an action that returns a view that goes to get the company selection for the specified employee - that way the overall view never sees the company data, that becomes a separate encapsulated problem - at least in terms of loading the data.
I think in this case where you're adding the employee either tweaking the model or adding the company list as supplementary data to the ViewData is sufficient, but for editing - assuming its required - rather than inserting you want a company selection list (all the companies with flags to indicate which are currently selected) rather than just a list of companies and at that point it all gets a bit more interesting

MVC Model: submitting multiple objects to the View

I'm not sure if there is a difference in these two methods. If so, which would be considered the better practice when submitting more than one object to the View.
Having the controller make separate calls to the datalayer for each object model and then wrapping the objects in a model to send to view.
Defining a "presentation" model and having the controller call that single model to send to the view.
other...?
I'm assuming here that you have a view that presents some information from more than one model, perhaps in a list format. For example, you may have a model of a customer which has a set of contacts, but in your list you want to choose to show some of the customer details along with the name and phone number of the primary contact. What I would typically do in a situation like this is define a specific "presentation" model that consists of just those details that I may want to show in this combined view. It would typically be a read-only model. Using LINQ to SQL I might even define this as a table-valued function (to support search) and associate it with a view that encapsulates the join of the various tables. With both you can add the view-based "presentation" model to your DBML and associate the table-valued function with it as a method on the data context.
I prefer doing this because I believe that it is more efficient in terms of queries to construct the query on the server and simply use it from the code. If you weren't using the table-valued function for searching, you might be able to construct the query in code and select into a "presentation" class. I would favor an actual class over an anonymous type for ease of use in the view. Getting the properties from an anonymous type in the view would be difficult.
You should send to the View a single object, sometimes termed a ViewModel object, containing all the data (including domain model objects) that the view will need.

Resources