Who owns the ViewModel in an MEF application - viewmodel

I am designing an application (Silverllight or WPF, still debating) but I am stuck at a design issue and was if wondering you could provide your opinion on it....
Here's the scenario. This is an Employee management application for HR. Once the application is ready, HR may ask for more features to be added(which most of the time means, more data). Say there is an employee form that saves employee record in the
database.The employee form has an associated EmployeeViewModel that it communicates with. The EmployeeViewModel uses Entity framework to persist its data in the database.
Now if the HR wants to add a new set of fields say "Spouse Information", I plan to provide a plug-in that HR can simply add to the form when available. This plug-in, SpouseInfo is sort of a usercontrol with a view model of its own.
The problem is who owns the ViewModel here.
a. Do I make SpouseInfo completely independant. Whenever Employee form is Saved or loaded, SpouseInfo calls its view model and loads or saves the data. In this case before it can save or load the data, It would need the EmployeeId from the Parent form before the data can be saved (which means, let the Employee form save the data first and then pass the Employee Id to SpouseInfo)
Or
b. The Employee form owns the ViewModel for SpouseInfo. That being the "parent entity" it is responsible for loading and saving the "Child Entity" i.e. SpouseInfo viewModel.
Thanks,
A

This is really a design choice. The fact that you are using MEF doesn't mean you don't have to decide what "ownership" makes the most sense for your application, and which components should be responsible for others.
That being said, I would probably make the "SpouseInfo" information conform to a known interface, and use that interface (loaded via MEF) from the main Employee's View/ViewModel. This would allow any injected control that was an employee dependency to be loaded at runtime, something like
public interface IEmployeeDependant
{
FrameworkElement View;
IPersistWithParentID ViewModel;
}
If you imported that via MEF, you could handle layout easily enough, and call into the VM directly with the correct required information (EmployeeId, probably) to persist the "sub" ViewModel.

Related

ASP.NET MVC 3.0 - Maintain model state

Am new to ASP.NET MVC 3.0. Request expert's view on the below mentioned scenario.
I have a customer details page, where only Name is editable. There are 10 other customer properties that are non editable and displayed using SPAN. When user submits the page, I need to update only the Name.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
Anyone tried caching model (or viewmodel) using session id? Is it a good practice?
You are almost thinking in right direction.
If am using EF, I will have to load customer again, overwrite name and then save. Otherwise I will have to maintain customer model somewhere.
In Update Method **Load Customer again and update name Only as required and then save
**For 2 reasons
The first and most important rule is 'don't trust user data'. and
Concurrency and to avoid saving old data. See this example
Instead of using Session, I will suggest to use Hidden Field for record LastUpdateDateTime and Customer ID which will be posted back in the model to retrieve record and verify LastUpdatedtime with database record
Tipically, you should use a view model different than the database model. Having said that,in your current case the situation is very simple, submit only the name to the controller and then set the Name property of the object you get from EF with the submitted name.
Caching the view model or the model isn't your concern. The database model caching is handled by EF, your problem is mainly a lack of clear application layering. IN fact I strongly suggest to learn a bit more about the MVC pattern, basic application architecture (2-3 layering) and when and how to use a OR\M (which EF is).
use hidden inputs for other properties in your form. In that way you can get all properties binded to your EF entity and you dont need to get entity again from db.
#Html.DisplayFor(model=>model.x)
#Html.HiddenFor(model=>model.x)
or you can serialize the entity(if you use POCO entities) and set to hidden input. When you post back you should deserialize the entity.
My choice is always first one. :)

CodeIgniter MVC Model Logic

I have programmed in Rails, Django, Zend, and CakePHP. Also, Wordpress and Drupal.
Now, I am "catching up to speed" in as fairly large application in CodeIgniter.
Typically, my experience with MVC frameworks, has led me to believe that Models represent business logic in reference to actual database tables. In the CodeIgniter docs and in the code base I'm dissecting I see models created that represent something as vague as a page. A lot of the business logic is written directly into those models and they incorporate other actual data models. I'm not sure this is ideal and following MVC.
Should models be created beyond data models?
Also, lets say I have a data model representing a user (user table in DB). In that user table there is a column called gender of the type enum('male', 'female'). Now I want to populate a dropdown with the gender options from the enum column.
Where is it most appropriate to put this logic?
The user model is an object used to represent a single user or row in the db... right? So it doesn't seem fitting to include a function in the user model/class called "get_gender_options", because, while the function is related to the user table, it is NOT relevant to a single user object. In Zend this kind of logic could be built into the form object itself.
There is not "right" answer, just one we can consider the most appropriate...
I would probably just put the "get_gender_options" in the model, rather than sticking it in the view for the form. To keep it DRY but not put it in the model, I would create a helper to hold this.

MVC3 (Models) ...what is the right way to display complex data on the view?

I’m having a philosophical problem with understanding how to use Models on MVC3.
I believe the problem lies from the fact that I come from WebForms :--)
Let's say I have 10 tables on my DB and as expected when I get them into my EF4, I get those Entity classes that represent the tables (and all their FK integer values).
When I want to display data on the View, I cannot display a select * from table because those FK integers means nothing to my users …and also because some data lies on related tables.
So my understanding is that I can create a Stored Proc, create a Complex Type that represent the actual data to display, coming from separate tables via different SQL joins.
QUESTION 1:
On the view, id MVC compliant to use as #model ..that Complex Type?
or shall I always use Models that are created on the Models folder? And if so, does that mean that I have to replicate the Complex Type on a new model inside the Models folder?
Question 2:
Is this the right way …to create specific SP to collect data that will be displayed or ..is it better to use linq and lambda to be applied to the EF4 Types that come from importing the DB into the EMDX designer.
Thoughts ??
FP
The correct way is to always define view models. View models are classes which are specifically tailored to the needs of a given view and would be defined in the MVC application tier. Those classes would contain only the properties that would be needed to be displayed by the view. Then you need to map between your domain models (EF autogenerated classes?) and the view models.
So a controller action would query a repository in order to fetch a domain model, map it to a view model and pass this view model to the view. Top facilitate this mapping you could use AutoMapper. A view shouldn't be tied to a domain model and always work with a view model. This works also the other way around: a controller action receives a view model from the view as action argument, maps it to a domain model and passes this domain model to the repository in order to perform some action with it (CRUD).
So a view model could be a class that is mapped from multiple domain models or multiple view models could be mapped to a single domain model. It all depends on how your domain looks like and how do you want to represent the information to the user.
As far as validation is concerned, I distinguish two types: UI validation and business validation. As an example of UI validation is: a field is required, or a field must be entered in a given format. A business validation is : the username is already taken or insufficient funds to perform wire transfer. UI validation should be done on the view models and business validation on the domain models.
I'm not sure why you need to use a stored proc, LINQ to Entities is able to generate complex types without needing to create stored procs (in most cases). You select subsets of data, just like you would with regular SQL.
As Darin says, the use of a View Model is appropriate for situations where you have a lot of complex data that isn't represented by a single entity. This View Model would contain multiple entities, or even multiple collections of entities. It all depends on how your data needs to be consumed.

Why Two Classes, View Model and Domain Model?

I know it could be bad to use domain models as view models. If my domain model has a property named IsAdmin and I have a Create controller action to create users, someone could alter my form and get it to POST a IsAdmin=true form value, even if I did not expose such a text field in my view. If I'm using model binding then when I committed my domain model, that person would now be an admin. So the solution becomes exposing just the properties I need in the view model and using a tool like AutoMapper to map the property values of my returning view model object to that of my domain model object. But I read that the bind attribute on a class can be used to instruct the Model Binder which properties it should and shouldn't bind. So what really is the reason for making two separate classes (domain model and view model) that essential represent the same thing and then incure overhead in mapping them? Is it more a code organization issue and if so, how am I benefiting?
EDIT
One of the most important reasons I've come across for a View Model that's separate from the Domain Model is the need to implement the MVVM pattern (based on Martin Fowler's PM pattern) for managing complex UIs.
I have found that while my domain model gets me 85% of the way to having the fields I want, it has never covered 100% of the values I want on my view. Especially when it comes to permissions and whether or not a user should have access to certain portions of the view.
The design concept I attempt to follow is to have as little logic in my views as possible. This means I have fields in my view model like "CanViewThisField" or "CanEditThisField." When I first started with MVC I would have my domain model be my view model and I was always running into the scenario where I needed just one or two more fields to make my view less cluttered. I've since gone the View Model/Model Builder route and it has worked wonderfully for me. I don't battle my code any longer but am able to enhance my view model as I need to without affecting the domain model.
Another good reason to have a ViewModel is paging large sets of data. You could pass the view an array of Person ( Person[] ) but metadata such as the number of pages, the number of the current page, the size of the page would not belong on the Person class.
Therefore a PersonListViewModel would solve this issue.
A ViewModel holds only those members which are required by the View. They can usually be thought of as a simplification or a "flattening" of the underlying domain model.
Think of them like this:
ViewModel: this is the data that is appropriate to render on this
view
Domain model: this is all the information my application needs
about this entity in order to perform all it's functionality
For example, my Order class has a member called Customer which is a composition association, that is, my Order has a Customer. This Customer object has members such as Firstname, Lastname, etc... But how would I show this on a "details" view of the order or a list of Orders and the Customers who placed them?
Well, using a ViewModel I can have an OrderListItemViewModel which has a CustomerName member and I can map the combination of Firstname and Lastname from the Customer object to this. This can be done manually, or much preferably using Automapper or similar.
Using this approach, you can have multiple Order ViewModels that are specific to different views, e.g. the Order list view might render the customer name in a different way to the Order details view.
Another advantage of ViewModels is that you can cut down on extraneous data not required of the underlying domain object on a view, e.g. if I'm viewing a list of orders, do I really want to see all the customer's contact information, billing details, etc...? I guess that depends on the purpose of the list but, probably not.
Sometimes you need to display the data in a specific manner (ie, displaying a date in the format mm/dd/yyyy vs. yyyy/mm/dd) and often it is easier to make this property in the view and not in the domain model, where you would (or should) have a mapping to a column in your db.
you need to remember
that your domain model classes are only used internally; that is, they are never sent to the
client. That’s what your service model types (View Model types) are used for—they represent the data that will be going back and forth between the client and your service.

Model Data Type versus View Control

I have having a little trouble wrapping my head around the design pattern for MVC when the data type of the model property is very different than what I wish to display in a form. I am unsure of where the logic should go.
Realizing that I am not really sure how to ask the question I think I will explain it as a concrete example.
I have a table of Invoices with a second table containing the InvoiceDetails. Each of the InvoiceDetail items has an owner who is responsible for approving the charge. A given invoice has one or more people that will eventually sign off on all the detail rows so the invoice can be approved. The website is being built to provide the approval functionality.
In the database I am storing the employee id of the person who approved the line item. This schema provides me a model with a String property for the Approved column.
However, on the website I wish to provide a CheckBox for the employee to click to indicate they approve the line item.
I guess my question is this -- how do I handle this? The Model being passed to the View has a String property but the form value being passed back to the Controller will be of the CheckBox type. I see two possible ways...
1) Create a new Model object to represent the form fields...say something like FormInvoiceDetails...and have the business logic query the database and then convert the results to the other type. Then after being submitted, the form values need to be converted back so the original Model objects can be updated.
2) Pass the original InvoiceDetails collection to the View and have code there create render the CheckBox based on the value of the String property. I am still not sure how to handle the submission since I still need to map back the form values to the underlying database object.
Maybe there is a third way if not one of these two approaches?
To make the situation a bit more complicated (or maybe it doesn't), I am rendering the form to allow for the editing of multiple rows (i.e. collection).
Thanks for any insight anybody can provide.
You need a ViewModel, like #Justn Niessner suggests.
Your controller loads the complete model from the database, copies just the fields it needs into a ViewModel, and then hands the ViewModel off to the view for rendering.
I'd use Automapper to do the conversion from Model to ViewModel. It automates all the tedious thingA.x = thingY.x; code.
Here is an additional blog post going over in detail the use of ViewModels in the Nerd Dinner sample.
I believe what you are looking for is the ViewModel.
In cases where you are using a ViewModel, you design the ViewModel to match the exact data you need to show on your page.
You then use your Controller to populate and map your data from your Model in to your ViewModel and back again.
The Nerd Dinner ASP.NET MVC Example has some very good examples of using ViewModels.

Resources