clarification on spring mvc ModelMap - spring

public String addStudent( #ModelAttribute("HelloWeb")Student student, ModelMap model){
}
can somebody explain how does this work?
what is the use of ModelMap model?

ModelMap subclasses LinkedHashMap.
public class ModelMap extends LinkedHashMap{
}
Model is an interface. ModelMap is an implementation of the Model interface.
Basically when you have data in code and you want to make that data available to the rendering of your jsp page, you need to put that data somewhere so that it is available. That is what a Model is for. To hold that data you retrieved in your code. It is just a glorified map.
So example, I have a form with a backing object with data. The form has three drop downs that I also need data to fill the drop downs. That is 4 different objects. 3 Lists for the drop downs and one object for the form backing object.
If my code gets all this data, I put them into the Model's Map and now I can use them on my jsp page.
refer this for more info.
also refer here for detailed info.

An architecture pattern followed in web applications is MVC which stands for Model, View And Controller.
Model holds the data. View is your display and Controller controls the flow.
A model is generally a simple object which can be rendered on screen. For example, a simple update user preferences will hold data which can be contained in a domain or model object called as user.
However, when the views and interactions get complex, a simple object may not suffice. And a complex object is needed. This somewhat complex object contains some other objects. For example, a page like user's news feed dashboard may have to hold data about;
user (name, etc) held in some user object
user's preferences held in userpreference object which in turn can be part of user
Some other objects - which may are not very suitable to be contained in the user object itself.
Basically, all these objects can make the model somewhat complex. So for better organization, these can be stored as name value pairs and packaged inside a single Map. So the page can refer to the required keys and get the object it needs to render.
ModelMap is this kind of a container object

Related

MVC architecture - patterns

I need some help with MVC architecture. I use the following architecture for an object named User.
UserRepository -> IUserRepository -> UserService -> IUserService -> UserController
The User object comes from my database and I'm using EntityFramework. I have a function that returns a list of users Return_All_Users(). One of the fields that gets returned is "UserType". This comes out as a number, but when I show the list in my Index.aspx page, I would like it to show as a string. The number for "UserType" needs to look into a Dictionary to find the string that goes along with the number like "Administrator" and I would like this string to show in my Index page.
How would I go about doing this? I'm currently using this function:
public IEnumerable<User> Return_All_Users()
{
//my code here
}
I had another post for a similar question, and it was suggested that my IEnumerable should return a string, not the User object. I tried that, but then I'm working with a Dynamic model and I didn't want to do that. Nor do I know how to work with a Dynamic model, so I thought maybe there is a better way of doing this.
Should this happen in my UserService? Maybe I need to create a new class called NewUser, and define the UserType as a string, then instantiate a new NewUser and pass the value from User. Before the UserType is passed, I would look in the dictionary and get the correct value for the key.
Should I do that, or is there a better way?
After I posted this question, I just thought of doing this with a stored procedure. Maybe use a stored procedure in my database to return the data, as opposed to looking up my data straight from my database table.
I would create a View Model UserView that was formatted to the representation of how your view would best use that data. You could perform the mapping from User to UserView within your Repository or Controller depending on where you prefer doing this kind of mapping.

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.

How to get data to my view that comes from more than one object?

So I have read some of the similar asked questions, but I don't know if the right questions were asked. It appears there are different ways to get data from multiple entities passed into your View Model, but I want to go about it the correct way.
I basically have 2 entities available in my controller, and I need to pass different information from both entities to my view. I have read about creating a SomeNameViewModel class that would be instantiated in my controller ViewResult method. With the SomeNameViewModel object assigning the data into a single object to pass to the View Model
Example:
public ViewResult List()
{
var vm = new SomeNameViewModel {
products = _prodRepo.All();
catName = <Some Expression>;
return View(vm);
}
But is this the best practice way to go about this?
I am using Nhibernate: So would this be better handled in my Fluent Mapping so that I have access to the other entity through the one-to-one mapping?
Using a model per view is a common (and good) way to go about providing data to your views. View models can encompass values from more than one entity type and may contain ancillary data as well. You might want to also consider using view-specific models for any entities contained in your view model to further isolate your view from your domain objects. This way you can provide to your view exactly the data they need and no more and, if your domain model changes, you may be able to only modify how the view-specific model gets updated from the domain model rather than propagating the change throughout your views.

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.

How should separated controllers access the model?

Given that I've got any number of controllers, how should they access the data saved in the model?
In a database driven application it's quite easy as all data can be fetched from one single object.
Should there be a namespace / singleton / global object which allows access to the data?
Should the model be passed to all controllers when they are created?
Some of the best practice being pass around is setting up a repository pattern like so within your model to abstract the data model form data mapping. I'd go into more detail but the first link gets you there.

Resources