How can I make my ViewModel map to my actual Model? - model-view-controller

I have a tab in my application, upon clicking which, the user's details are displayed (using the placeholder HTML attribute) to him inside editable text-boxes. The user can simply view them or can edit whichever detail he wants to.
Now my question is: should I create a View Model class for this scenario or should I use the actual Account model class? I guess I will have to create a View Model class as I will require only 'some' properties from the Account model class, but if I do so, how will I make it 'editable' and subsequently, map the edited properties(if any) to the actual Account model class?
Also, please tell me where exactly do I need to store the View Model class if I need to create one.

should I create a View Model class for this scenario or should I use
the actual Account model class?
Yes, it's best to create a model that represents the action you need and you do that to prevent under and over posting. So you work on properties where you expect users to work on. For example, if you have an AccountModel that has a lot of properties and you only need to work on ten of it on an add action and five of its properties on an edit action, then you create two ViewModels:
// your model or entity
public class AccountModel {
// the list of properties goes here
}
// your view models
public class CreateAccountModel {
public string Username {get;set;}
public string Password {get;set;}
public string Phone {get;set;}
}
// this model is for the scenario
// where you want users to edit their basic info
// but not the password (e.g. you have a separate
// functionality for changing the password)
public class EditAccountModel {
public string Username {get;set;}
public string Phone {get;set;}
}
Now to map your viewmodels to your actual model or entity, you can use mapper tools or do it on your own (tiring but an option for small models). Here are the steps:
You receive the model/entity from a post
You query your entity from your database
You copy the values from the viewmodel to the model/entity
You save the model/entity back to your database
where exactly do I need to store the View Model class
You can have it in your MVC project under the Models folder that was created. This is more of a preference really and there is no standard way of doing it - especially if you start layering your application. Put it somewhere where it makes more sense.

Related

How to pass data from page to page in Thymeleaf based spring boot application

I am developing application in Spring boot and i am using Thymeleaf as a template engine. Its like a Ordering application where user selects option on Page 1, Page 2 and so on and at last page i have to save all the previously user selected options to DB.
Can anyone suggest what will be the best design approach to pass data from one page to another should i need to use session ? I have Model objects defined for each page and i am passing to and from data using these model object .
I'd recommend completing this short tutorial (https://spring.io/guides/gs/handling-form-submission/). It illustrates how model attributes can be sent from a client page to the server as well as from the server to the client page.
Once the model is populated to its final state, the model can correspond to a table in your database as is illustrated in this tutorial (https://spring.io/guides/gs/accessing-data-mysql/) via Hibernate and the #Entity class.
Cheers!
I did something like below
#Component
#Scope("session")
public class Cart
{
// simple POJO fields
}
and then use this inside the Controller i want
#Scope("request")
public class SessionController
{
#Autowired
private Cart cart;
#RequestMapping("/addToCart")
public String addToCart(#RequestParam("id") int id)
{
//
}
}
since the scope of cart is session so i can use this model object to whichever controller i want put the value in cart object get the value from it wherever i want.
Sessions work great as well. Cheers!

MVC: Should logic be placed in the Model or Service layer?

Recently I talked with a co-worker and had a conversation regarding Model View Controller paradigm. We were talking about proper organization of files and such and I mentioned that I thought that "skinny controllers and fat models" were the way to go. Meaning that the controller just calls the "fat models" methods which contain business logic:
public class CreditCard {
//instance vars
//constructor
//getters
//setters (if you want mutability)
public boolean makeCreditCardPayment(Cart cart) {
//implementation details...
}
}
My co-worker mentioned otherwise. He said that the models shouldn't really be "fat" and contain any other business logic. The model should just be a data-structure and contain zero methods (obviously if your are in Java you need setters and getters). Just like a C-style structure, obviously with data fields that have mutators and accessors:
public class CreditCard {
//instance vars
//constructor
//getters
//setters (if you want mutability)
}
public class PaymentService {
public boolean makeCreditCardPayment(CreditCard card, Cart cart) {
//implementation details...
}
public boolean makePayPalPayment(PayPal paypal, Cart cart){
//implementation details...
}
Or even have a PaymentService for each type of payment that implements an interface. So something like 'CreditCardPaymentService implements Payment' or 'PayPalPaymentService implmeents Payment'.
To me, using the service method way seems like we are just going back to procedural style programming.
Another example would be a 'Vehicle' object with a getSpeed method compared to a service which takes in a Vehicle object and returns the speed.
I have looked over other stackoverflow answers but they have differing answers. In one question, one of the users mentioned that the service layer is part of the models part of MVC. I am looking for other answers.
I've encountered many different philosophies claimed to fall under the MVC umbrella.
My position:
Models directly manage some kind of backing store, and should contain mutation and validation logic.
Controllers should look like a model to other controllers and views (making them composable), and contain any additional logic required to validate the mapping from the controller's interface to a model's interface.
Views just contain whatever state and logic they need to function; their purpose is to display data and collect input.
It looks like your PaymentService is trying to be more than one controller, so I'd go the separate CreditCardPaymentService and PayPalPaymentService route.

MVC design pattern model logic

According to the MVC design pattern, if we create a user (database work) and we have to send a mail with an activation code to the user, would this fit in the model or in the controller, after the model created the database record?
The MVC pattern is used to create an abstraction between the business logic (the model) and the GUI (the view). The controller is just an adapter (google adapter pattern) between those two blocks.
Hence the controller should only have code which is used to fetch the required information from the controller and adopt it so it fits the view. Any other logic should be in the model.
That only make sense if you understand that the model is not a single class but all of your business logic.
Example (implementation specific, but I hope that you understand):
public class UserController : Controller
{
// notice that it's a view model and not a model
public ActionResult Register(RegisterViewModel model)
{
UserService service;
User user = service.Register(model.UserName);
return View("Created");
}
}
// this class is located in the "model"
public class UserService
{
public User Register(string userName)
{
// another class in the "model"
var repository = new UserRepository();
var user = repository.Create(userName);
// just another "model" class
var emailService = new EmailService();
emailService.SendActivationEmail(user.Email);
return user;
}
}
MVC and MVC-inspired design patterns are combination of two layers:
Presentation layer
Model layer
Presentation layer is made up from views, controllers and (mostly in web-oriented solutions) templates. This layer deals with user interaction. It recognizes user input, produces responses and governs other aspect of user interface. The controllers, based on user interaction, change the state of model layer.
The model layer deals with domain business rules and interacts with different forms of storage. Model layer, just like presentation layer, is no any single object or class, but a group of structures with different responsibilities.
In this case, it would make sense for the service, which deals with user management, to use the different structures, that would both send the verification email, create an account and store this newly created user.
Services in model layer act like the barrier, that isolated the presentation layer from business logic. They deal with interaction between domain objects and storage abstractions (data mappers, repositories, units of work, etc.).
TL;DR
Email, with activation code for the newly created user, should be sent from model layer.
The controller is an object which simplifies and delegates messages to the model objects.
What you will have is an Interface object (or boundary object) within your model that represents the link between two systems (your system and email). class EmailClient. Your model objects will collaborate with this object when required.

How to handle service-layer validation in MVC3

I am working on a project which requires different validation sets for the same model, and we're trying to find the best solution to handle it.
A simplified example could be using our Customer DTO:
public class Customer
{
[Required]
public string FirstName { get; set; }
[Required]
public string LastName { get; set; }
[Required] // Only required on some views
public string Title { get; set; }
}
In our first view, all fields are required, as they're shown in the DTO using DataAnnotations.
In our second view, FirstName and LastName may be required, but Title is optional, and may not even be represented on the view.
The complication comes in, that we want to have validation rules live in our service layer (so that we can provide an API at a later point utilizing the same validation), which can access the data annotations, and validate against them, reporting back up to the UI if they don't validate.
So far, the winning method is:
Every view has a dedicated viewmodel, which the DataAnnotations exist on.
The viewmodel then maps our domain objects using something like Automapper.
The domain objects are then passed to the repositories and services to have actions taken upon them.
This also means:
Validation would not occur in the service layer, since by the time the objects got there, they would be domain objects instead of viewmodels.
Is there some better way that we should be handling this for an enterprise application? We have yet to find a solution.
You can't cram all your validation into one place when it's context-specific. Use your winning method, but also have your entity services do appropriate validation in that layer.

Extend linq-to-sql partial class to avoid writing a property?

I have a linq-to-sql class. I have a property "Password" for which I want to call the underlying ASP.NET Membership provider. Thus, I do not want this property written out directly but via my own code. I basically want to create a facade/proxy for this property such that I may use the underlying membership provider or a custom stored procedure.
I want to accomplish without modifying the LINQ-TO-SQL designer generated code, if at all possible.
It is possible. You can add your properties and methods to linq generated class using partial class mechanism. Linq generated classes are marked partial so you can add class members with:
public partial class YourLinqClass
{
// your methods and properties. refer linq properites and methods with "this."
// example:
public string Password
{
get
{
int id = this.UserId;
string password = // ... get password
return password;
}
set
{
// ...
}
}
}
You have to place the partial class in the same namespace as the rest of dbml.
The best option is to remove the property from the designer and write it in code, in the partial class, as described by PanJanek.
However, if you do it this way, you are pursuing a bad design. You're introducing a dependency into your entity class that breaks layer encapsulation. Entity classes shouldn't know about providers any more than they know about the DataContext that loads them. They aren't really meant to be anything more than containers for data going in and out of the database.
You should consider making a separate class that wraps the entity, the context, the username provider, and whatever other services you require, and in that class retrieve the username and do the required operations to your entity.
It looks like it might be possible to create a custom DataContext to handle this situation.
http://weblogs.asp.net/scottgu/archive/2007/07/11/linq-to-sql-part-4-updating-our-database.aspx
There are partial methods for the individual properties as, well and an OnValidate method.
In my case, I think the best solution is to throw an exception in the property changing method and add a public method for setting this individual property. This solution while not perfect will avoid touching the SQL generated code, where the property could be set to readonly or the setter removed.
Other suggestions welcome.

Resources