ASP.NET MVC: Where do you assemble the view model for a view? - asp.net-mvc-3

From inside to outside, these are our MVC app layers:
MS SQL / Tables / Views / Stored Procs
Entity Framework 4.1 (ORM) with POCO generation
Repository
Service (retrieve) and Control Functions (Save)
Routing -> Controller -> Razor View
(client) JQuery Ajax with Knockout.js (MVVM)
Everything is fine until I need to create a single ViewModel for step 5 to feed both the Razor view as well as the JSON/Knockout ViewModel:
Header that includes all Drop down list options and choices for the fields below
Items - an array of whatever we send to the client that becomes the ViewModel
Since the Controller won't have access to the Repository directly, does this mean I create a service for each and every view that allows editing content? I'll need to get the POCO from the repository plus all options for each field type as needed.
It just seems redundant to create separate services for each view. For example, a viewModel to edit an address and a separate viewModel to edit a real estate property that also has an address. We could have a dozen forms that edit the same address POCO.
To make this question easier to answer, is allowing the Controller direct access to the repositories a leaky abstraction?

Well, so are your controllers going to have code that translates POCOs from Entity Framework into separate view model objects?
If so, then you should move that code to a separate class, and follow the single-responsibility principle. Whether that class is in the "service layer" or not is up to you. And whether you use AutoMapper or not is up to you. But these kind of data mappers should not be part of the controller logic; controllers should be as dumb as possible.
OK, now let's ignore the data mapping problem, and pretend you could always use your POCOs directly as view models. Then you would still want a service layer, because it would translate between
userService.GetByUserName("bob")
in your dumb controller, and implement that in a specific manner by returning
userRepository.Users.Single(u => u.UserName == "bob")
Putting these together, your UserController ends up taking in IUserService and IUserDataMapper dependencies, and the code is super-dumb, as desired:
public ActionResult ShowUserPage(string userName)
{
var user = userService.GetByUserName(userName);
var viewModel = userDataMapper.MakeViewModel(user);
return View(viewModel);
}
You can now test the controller with stubs for both dependencies, or stub out IUserDataMapper while you mock IUserService, or vice-versa. Your controller has very little logic, and has only one axis of change. The same can be said for the user data-mapper class and the user service class.
I was reading an article this morning that you might find somewhat illuminating on these architectural matters. It is, somewhat condescendingly, titled "Software Development Fundamentals, Part 2: Layered Architecture." You probably won't be able to switch from a database application model to the persistent-ignorant model the article describes and suggests. But it might point you in the right direction.

i personally always inject the repository/repositories into the controller. i'm not sure why you would want to have a service layer between the repository and the controller. if anything you would use specifications.
once you've done that, check out automapper. its a mapper that, once properly configured, can map your domain model to your viewmodel, and back again.

Related

How should the MVC pattern work?

I have searched and searched but got no answers: How should the MVC pattern work?
So long I got two examples out of many similar ones: one of them suggests that the view should be updated by the controller, but the model is directly updated by the view, and another one suggests that the model should be updated by the controller, but the view should be updated by the model.
I have learned that the view should display content from the model fetched by the controller, and the model content would be altered by the view and updated by the controller.
It's been a year, and I got no answers. Maybe because the question is kinda opinion-based, or maybe because it didn't get much attention.
But ever since then I searched and studied more and more about best practices and design patterns, and now I feel confident enough to answer my own question.
Q: So, how should the MVC pattern work?
A: It should work the way you design it.
The MVC pattern defines three vital types of components: the Model, the View and the Controller:
The Model is what holds and manipulates the data you're working with: it handles persistence methods (writing/reading or CRUD) and has all the properties that your file/database table has;
The View is what displays the Model in a human readable way: it binds his visual components' values to properties of the Model;
Finally, the Controller is what notifies the View of changes on the Model, or notifies the Model of changes on the View: basically it's a sort of messenger, notifying two parts of each others' actions.
Now, how's the usual data flow of a MVC application?
The user changes a component value on the view;
The View queries the Controller about the value that the user passed;
The Controller then notifies the Model that it wants data about the value that the View passed;
The Model interacts with the database and gets the corresponding values (if they exist). After that, it notifies the Controller that it finished whatever it was doing;
The Controller notifies the View that the Model has been updated;
The View updates its' components accordingly, changing whatever values that may have changed.
That was only the reading flow, the writing flow is similar but a bit different:
The user changes values on the View;
The View sends those values to the Controller, saying that data changed and it should be persisted;
The Controller notifies the Model about the data changes, and passes the message along;
The Model then updates the database with the new/updated data, and notifies the Controller;
The Controller notifies the View that the Model has been updated;
The View displays a message to the user, saying that the operation was sucessful.
Now, when I first asked this question, I was with a Java-heavy mindset, so I wanted to know how would I go about implementing this in Java:
DAOs and Java Beans. You write the views and the controllers, but the models are split between data objects (Beans) and persistence objects (DAOs);
Java Beans with embedded persistence methods. You write the views, the controllers and the models. The models are Java Beans that have whichever persistence methods you need (the most basic ones being insert, select, list, update and delete).
So, my final answer is: There's a lot of correct ways of implementing the MVC pattern. But there's a series of guidelines you should follow if you want your implementation to be correct.

Spring best practice to separate model from view in controller and jsp?

Is it a good practice to use Spring Controller class(with #ModelAttribute) and the jsp to prepare model at the same time or the model has to be prepared only by Spring and the view from the jsp?
The idea comes from this topic . I have a Controller class:
#RequestMapping(value = {"", "/"}, method = RequestMethod.GET, params = "mode=create")
public ModelAndView showCreatePage(#ModelAttribute("createForm") ApplicationCreateForm form)
{
return customMethod("some string");
}
and in my jsp I have:
<jsp:useBean id="createForm" scope="request" class="com.example.ApplicationCreateForm"/>
I do not need to populate the form with the information to be present to the user all fields are empty.
So from what I uderstand I have been declared ApplicationCreateForm bean twice, with the same scope - request.
Is it a good design practice to use both at the same time? Is there a reason for that? Does the second declaration(in jsp) give me more power, for example to override the model or it is complete unnecessary? Does the second declaration overrides the first one when both are present?
There are many things wrong with this implementation.
Is it MVC?
If JSP know about Model, why do we need controller. Lets remove the routing engine and use JSP directly to consume Model. But then the application will be monolithic. I believe you do not want that. We have two major flavours of MVC. In both, controller is the front facing object. It receives the command, interprets it, works with data layer and gets Model. If required the Model gets converted into a viewModel and then this object is passed to the view.
Why viewModel?
Say we are implementing paging on screen. We are showing list of persons. Person is your model here but your view also need to know page number, page size etc. Your model thus may not fit directly in this case.
Say we need data from multiple tables to shown on screen. This data is related in some way. Now will you pass separate model objects to view and let it do all the business logic? Ideally no.
Should not the design support DTO or ViewModel or Commands and Queries?
We want our application to be designed properly. As stated above we need to send data to view or clients (REST) after processing. Processed data may not map to you domain until unless we are just creating a CRUD stuff. What if you want to implement CQS or CQRS?
Where is separation, where is SOLID?
If my view is performing business logic then where is 'S'? If view knows about model and need to be changed in slightest of changes in model then where is 'O'?What if I want to separate queries from command (CQS) and scale the two things separately?
To conclude I would say, yes you can do this but it is not good if you are developing a decent size application or you think it will eventually be one. I have seen people using model entities starting from ORM, to controller to view. It will work but the question is do you want a monolithic and tightly coupled application. As per my experience the presentation logic (view) has very different logic and need of data in comparison of controller and same goes for your data access layer.
I think you should prepare your model fully in spring controller. Then view should be as passive as possible, ie. only showing model attributes received from controller while having no further knowledge about application logic. This approach gives you clean separation of concerns and you view is as independent as possible and can be easily switched for different view technology - eg. thymeleaf or freemarker templates. The whole idea of MVC is to separate presentation layer and by leaking business logic to view you create unnecessary dependencies.
Your view should be as simple as possible, as the logic leaked to view makes it very hard to test and reuse. On the other hand, if your logic is nicely separated, you can test it easily and reuse it easily. Ideally, business logic should be completly independent on web environment.
By defining you are creating tight coupling between your view and class com.example.ApplicationCreateForm, using spring mvc you achive loose coupling between your controllers, view and model it might happen that you change you model name but you still have same properties in it which might be enough for view, in above case you will need to update your view but it won't be required in case you are using Spring MVC.
Since spring comes with the concept of making things loosely coupled to make your code more testable, you should always keep in mind that separation of concern is your priority. So it is always the best practice to prepare your model fully in Controller, not in views.
Keep thing simple , make your controller responsible for preparing your model, and keep your views to display the model only.
So, a big NO to your question. The second declaration isn't going to make you powerful, rather help you to be tied up.

How to model a Database View in ASP.NET MVC

I have to gradually replace an ASP.NET Web Forms application with an ASP.NET MVC3 layered application. Let's take into consideration just the Repository layer.
In my new MVC application I have one project for Data (name MVC.Data) and one for Web.
In the MVC.Data I have an edmx file with the EF classes, which models just the DB table (no views), and a Respository class myRepository which provides methods that perform simple queries.
In the old Web Forms application I have a GridView which is filled using as DataSource an SQL database view.
In order to have the same result in my new MVC3 application, I have two options:
1) Create a Service layer (and project MVC.Services), where I have a method that fill a new class myViewClass which contains all the fields of the SQL DB view and give it to the controller.
2) Create a class within the MVC.Data project which is directly filled by its constructor by using LINQ statements directly against the EF classes.
I read about the factory pattern and the 1st solution seems the most appropriate, however many people always suggest not to create a Service Layer if it is not needed. What is the best choice in this case?
Actually building the view model should be done in a mapping layer. Basically your controller action might look like this:
public ActionResult Index()
{
SomeDomainModel model = repository.GetSomeDomainModel();
SomeViewModel vm = Mapper.Map<SomeDomainModel, SomeViewModel>(model);
return View(vm);
}
The view model is defined in the MVC project as it is a class that is specifically designed to meet the requirements of the given view.
The Mapper.Map<TSource, TDest> method I have shown in my answer comes from AutoMapper which I use in my project but you could define any custom mapping layer you like.
The mapping layer must also be part of the MVC project as it must be aware of both your domain models and your view models in order to perform the mapping.
As far as the service layer is concerned, you could use one when you have some complex business operations which could be composed of multiple simple repository calls. But some might argue for the existence of a service layer at all. I think that both approaches have their pros and cons that must be evaluated when designing a system and most importantly take into consideration the specific context and scenario you are designing.

Add ASP.NET MVC Routed URLs to view-model objects (for use in JSON)

I'm writing an application which uses ASP.NET MVC with JSON.NET as the server, sending JSON to the client which is read by Knockout and then displayed with data-bindings. This is all working wonderfully, except for one problem:
I have a class Customer which is used to generate a ReviewAuthorViewModel class - the latter is meant specifically for JSON serialization and removes unnecessary fields, circular references, etc. On the client, I want to render a link to the Customer's profile page, with the URL coming from a defined MVC route "user/{username}". Because I'm sending this via JSON, I don't have a .cshtml page in which I can call Url.Action.
The question is: For an arbitrary object, how do I most efficiently/elegantly get a URL for an action with some data, without a .cshtml view?
I'd prefer a solution that doesn't require extra code in each action, but that may be the only choice apart from recreating the routing tables client-side in JavaScript. Below are the things I've already tried, and what was unsatisfactory with each.
Solution Attempt 1
Call the UrlHelper.Action method in the ReviewAuthorViewModel class. However, the UrlHelper requires a request context. For the sake of separation of concerns, I don't want my view model to have a dependency on System.Web.Routing, nor do I want it to need a request context to function.
Solution Attempt 2
Create a class RouteInformation with members Controller, Action, and Data, and an interface IUrlViewModel with two properties, a get of type RouteInformation and a get/set string named Url. The view models needing links then implement this interface, and controllers look for view models of type IUrlViewModel and run UrlHelper.Action with the information from the view model's RouteInformation instance, storing the result in the Url property.
This one works but without reflection I don't know how to find view models implementing IUrlViewModel within other view models, and it feels very kludgy.
Solution Attempt 1 is the OK solution. In asp.net-mvc, view models are part of presentation layer, designed specifically for use with views. You should not worry about having view model depend on asp.net specific things. In fact, they should be coupled, as they should be designed to maximize simplicity of view generation and data exchange between web server and web client. And it's good solution to create separate view model and not use Customer class directly for clients. It wouldn't have been OK if Customer was dependent on Routing.
In fact, you could set that property in controller -
[HttpGet]
public ActionResult Get()
{
var viewModel = new ReviewAuthorViewModel();
viewModel.ProfilePageUrl = Url.Action("Index", "Profile");
// return viewModel;
}

Need expert's voice for mvc beginner about Controller & Model

I am quite new to MVC. I am having the following questions, please help me clarify those questions, thanks a lot.
Q1. Where should I populate my view model? e.g. My view model is very big, and contains a lot of the dropdown listbox, multi select list and the other few complex objects. I am currently populate them inside the view model self, by passing the model through the constructor, and load all the object data within the constructor. I also see my college populate the viewmodel inside controller. so I am confusing now, coz lots of people suggest to keep the controller small and skinny.
Q2. We are using the linq2sql as data access layer, should I use the table entity in my viewmodel instead of creating separate model class? Expert said it's bad, but if create seperate model class, I basically repeat them and I also need to copy those value to linq 2sql entity every time when I want to persist data, it's not that fun, too much work.
lots of people suggest to keep the controller small and skinny.
Yes. What people mean is that the controller should not contain any logic, except for model <-> view mapping. With model I mean the "M" in MVC.
Q2. We are using the linq2sql as data access layer, should I use the table entity in my viewmodel instead of creating separate model class? Expert said it's bad, but if create seperate model class, I basically repeat them and I also need to copy those value to linq 2sql entity every time when I want to persist data, it's not that fun, too much work.
No. You should not. Read my answer here: ASP.NET MVC Where to put custom validation attributes
Use a mapping framework for the model -> viewmodel conversion.
Update:
From what I understand, you suggest to assembly the viewmodel inside the controller (I mean call the business layer or repository to get my data) and use controller to call the business logic dealing with the data, am I right?
yes. The controller is really a glue between your business layer / repositories and your views. The views (and view models) should know nothing about them and the business layer / repositories should know nothing about the controller/view.
The controller was created for just that purpose. To create an abstraction between the user interface layer and the lower layers. Hence the only code that should exist in the controller is to make that possible (and therefore following the Single Responsibility Principle)
If you start adding that logic into your view models you start to add coupling between the lower layers and the user interface layer. Doing any changes in the lower layers will therefore also affect all your view models (instead of just the controller
your viewmodel should be a poco, and should most certainly not be handling the mapping of the model. if you don't want to map your model to your viewmodel in the controller i would suggest you look at something like automapper. it makes it easy.
once you've mapped from your model to your viewmodel, any extra properties that need to be set such as your lists should be set in the controller.
as i stated previously, definitely don't tie your viewmodel to your current orm or table structure. you never know what might need to be refactored, and if you can handle it via an automapper mapping instead of changing your view and viewmodel then you've saved yourself a significant amount of time.

Resources