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

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

Related

single view - page - showing data from a group of normalized of tables

What I hope is a basic question,
I am designing an MVC project with the entity framework and code first and in it has a number of normalized tables that later will make up a combined view.
For example say I have a table called JOBS. This table has foreign keys for a CUSTOMER table, a STATUS table, a JOBSTYPE table.
If I want a view (a page) that displays the job with the customer, its status and its jobtype how do I manage this outcome?
In other words if I want a page that shows the job, the customer and the jobs address (sourced from the address table - itself linked via a foreign key in the customer table) how do I do the view for this?
Further, with a focus on CRUD, If I want an update page how do I display a page that has text boxes to update things like the job's address or the status which are in different tables to the actual job table.... and to press a button on the page saying "update" and each table updating automatically..
Look forward to any help clearing the confusion...
Kind Regards
Simon
Just as the question, this answer is hypothetical as well. What you can do is have a look at your page design and figure out the columns/properties you want to show from multiple tables, you then create a ViewModel for this page, then you can write a LINQ projection query to bring the results as your viewmodel.
Another other option will be to use lazy loading all linked tables and render related entities, but this this approach you have to make sure that the EF context is not disposed till the whole view has rendered.
The ViewModel and Projection approach also works well with updates and your update action will take in your view model and translate back to EF entities for updating.
For translations from ViewModel to EF Model entities and vice versa you can use automapper

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.

Showing many tables in many dropdown lists. c#, asp.net-mvc, linq2sql

I want to use an example to explain what I want.
Assume I've following DB design:
Item (id, name, categoryID);
Category (id, name);
When user wants to create an Item (fill in form), I'll give a list of categories in a dropdownlist, and when user chooses one of the categories ASP.NET MVC will automatically bind categoryID, to the selected one. I need to present same dropdown list when editing the item with correct selected one.
Question:
But my DB is very big, and it requires around 30-40 (maybe even more) category-like tables, that contain just "id" and "name", and all tables need to be shown in dropdown list while creating some other object, and also needs to be presented while editing the object. Definitely above schema doesn't work, because it's tedious to write same logic 100 times with just different table names. (I'm using Linq2SQL)
Currently my solution is:
Make a view that's based in all such tables and in application I just call a function that construction dropdownlist from that single view. But it's still tedious to change view definition everytime I add a new table.
Do you guys think of a better solution for this tedious work, possibly using reflection or some other tecnologies.
It is not a problem "Definitely above schema doesn't work, because it's tedious to write same logic 100 times with just different table names."
If I were you, I will mark an addition interface on these class using "partial class" feature.
Then, I will write few extension method for the partial class.
If anyone interested in the solution:
I've used reflection to solve this problem.
I use reflection over DataContext to get the Table (by string name), and get its fields and construct the optionlist.

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