Who is responsible for parsing? The controller or service layer? - asp.net-mvc

The project I'm currently working on has a Core API which is used by everything: services, web, ...
This API has following layers:
Core
Core.Models
Core.DataProviders
Core.DataProviders.LinqToSql
Core.Utils
On top of this API is my ASP.NET MVC application. This looks like this:
Web
Web.Models (Some Web specific objects and logic. For example a class which builds a list of quarters to help me render a day in a scheduling table.)
Web.Extensions (Html Helpers, Controller base..)
Web.ViewModels (Composite objects to pass to the View.)
Web.Services (Layer which communicates with the Core and Web.Models. This layer builds ViewModels for my Controllers. Helps keeping my Controllers clean.)
Any serious flaws in this setup?
A more specific question: I need to parse some things coming from my View before I can pass them to the Core. Should I handle this in the Controller or in the Service layer?

Generally speaking data submitted from the view should be parsed by a ModelBinder, falling back to the Controller if using a ModelBinder doesn't seem to make sense.
Parsing in an application service makes sense if multiple sources can submit the data in the same format (like web service or file system persistance).

Related

ASP.NET MVC with Web API Architecture

Gurus,
Am newbie in MVC. I am developing a web application for an Order Management System. I have devised architecture to have the following projects as part of my solution:
Client (Presentation layer, MVC)
CrossCuttingServices ( framework components like logging, caching, Data, Class lib)
Data (Entity framework layer for DB interation, C# class lib)
Services (Services layer to be consumed by Presentation, Web API)
Q1. My question is, where should I create my entity classes or Models, which will be used across Presentation to Services to Data? Either in models of Presentation or in Web API service layer or as a seperate project (C# library)?
Q2. Also, let me know is there any generic implementation to invoke WebAPI services from Presentation controller.
Q1: You will be using the same entities throughout the entire solution so I recommend storing them in your Data project since it keeps all database related stuff bundled together separately from the remaining logic.
Q2: You could always send a request to the APIs to get the resulting data, it's essentially what they're there for.
I have decided to go with Architecture like
1. JS Enabled Presentation (webform or only HTML + JS)
2. Web API (Controller calling data services (EF+Repo) as my service layer for data, it can support my browser based front end and devices
Let me know any drawbacks on same
We have a similar problem, with a pretty complex domain model. As a result we have opted for
data entity models defined in a separate DomainModel DLL
UI mapper classes that map from datamodel to UI models
WebAPI mapper classes that map from datamodel to WebAPI models
An example of why we want this?
UI has concept of distributor catalogue item, which is a specialisation of catalogue item
WebAPI uses the basic catalogueitem datamodel, but then returns different data based on the specific resource [eg a search URL returns item ID and basic info; an item lookup URL returns full details for the catalogue item.
As a result of the above, the catalogueitem in our DomainModel is the full complete object, which the different "clients" then map as they see fit.
[This is in line with what Filip Stankovski said above]

Create a View against an API controller?

I need to create a website where some of it's pages should be accessible from external clients via an API, but I still want to make regular MVC Razor views to retrieve, display and manipulate the same data.
What's the best way to achieve this?
Update
What the API will have to expose is just data manipulation.
For the web pages, I still want to benefit from the razor chtml views, I prefer not polluting my views with redundant jQ or JS nor data- attributes that consume the data.
Just create an MVC project with the pages you want, and then create ApiControllers (from the Web API framework) to serve as RESTful endpoints. You can program your views to retrieve data from the API actions as JSON objects, and consume them with javascript. Other people can hit the same API actions and use the data in some other way.
If you want to start with a WebApi, and build basic views based on the same data that someone else could access via that API, you could inject your WebApi controllers into your normal MVC controllers, and invoke their methods to get the data that you need to build your ViewModels. This should work all right as long as your API controllers don't need to do anything "outside the box" like inspecting the Request object directly.
A more robust method would be to create a "Manager" layer that handles all the business logic of your application, and then have your ApiControllers be nothing but thin wrappers around calls to their respective Manager classes. This would add a little maintenance cost, but it would adhere to the Single Responsibility Principle a little better.
The easiet way is to use just MVC.
You can also combine MVC + WebAPI in one site.
The reasons to go with the first option is simplicity, and learning maintaining one framework and one set of abstractions.
However if you have any of the following requirements, adding Web API becomes interesting:
1. You want to do content negotiation for response types (say XML vs. Json for the same action).
2. You want to support CORS
3. You want a help page for your API.
4. You want to structure your Url space for your API with rest and resource centric approach (basically GET /resource rather than /resource/GetData).
5. Easier to unit test controllers and actions.
Both frameworks are built by the same team, they both support attribute routing and many similar concepts, and both work well together with one another. I've seen folks take both approaches successfully. Also note that visual studio has templates that combines both of them from the get go.

What role does MVVM play in ASP.NET MVC 4 web applications?

While I'm reading the book "ASP.NET MVC 4" I'm wondering about MVVM. I started googling and cannot find any books about developing web applications using MVVM, so I must be missing a bit of information here.
From what I understand, MVVM is used in web applications on the client side via knockout.js and other frameworks.
If however I was to develop a Windows Phone application, I could use MVVM directly without using MVC.
Does that mean, the concept of MVVM / data binding just does not apply to client-server web applications?
MVVM is really sort of a subpattern. There's not really any "MVVM" web app frameworks out there. They're all MVC and you pretty much just incorporate a view model if you want one.
With ASP.NET MVC, in particular, you just create a class, generally with a name in the form of [Model Name]ViewModel or [Model Name]VM. That class will have only the properties from your model that you'll need to work with and anything extra that doesn't make sense to put on your actual database-backed model, like SelectLists, etc.
In your action, you just pass an instance of this view model to your view instead of your model:
return View(viewModelInstance);
And, of course, make sure your view accepts that:
#model Namespace.To.MyViewModel
The only slightly complicated part is wiring the view model to the model (i.e., getting data to/from the view model/model. You can do this manually by explicitly mapping the properties, or you can use something like AutoMapper.
MVVM is the standard design pattern for WPF/Silverlight development, and should not be confused with MVC for ASP.Net development.
The two may sound similar and share some common parts, but they are two different design patterns.
From what I learned about knockout.js, it was designed to create "data bindings" similar to what you would use in WPF/Silverlight development, which is why the MVVM design pattern applies there.
To quote from another answer of mine regarding the differences between MVVM and MVC
In MVVM, your code classes (ViewModels) are your application, while your Views are just a pretty user-friendly interface that sits on top of the application code and allows users to interact with it. This means the ViewModels have a huge job, because they are your application, and are responsible for everything from application flow to business logic.
With MVC, your Views are your application, while your Controller handles application flow. Application logic is typically found in ViewModels, which are considered part of the M in MVC (sidenote: the M in MVC cannot be considered the same as the M in MVVM because MVC's M layer contains more functionality than MVVM's M layer). A user is given a screen (View), they interact with it then submit something to the Controller, and the Controller decides who does what with the data and returns a new View to the user.
MVC is a one-way data-binding system.
Fill your Model in Controller, then pass it to View.
MVVM is a two-way data-binding one.
Fill your Model, use it in View, when the View state's changes, your Model update automatically.(Vice-versa)
Does that mean, the concept of MVVM / data binding just does not apply to client-server web applications?
No, you can apply the MVVM pattern to client-server web applications.
In fact Asp.Net MVC actually kind of does use this pattern - when the controller creates the view, it can pass in a "view-model". This view-model is often a POCO data object with all the data that a particular view needs, drawn from the model (database). The view uses this data to render the html page.
MVVM on wikipedia says it was introduced by Microsoft with WPF. Specifically, the view binds to properties on the view-model. The view-model then maps this to the database. By this definition then, Asp.Net does not exactly match that. Client-side frameworks like knockout.js and vue.js do support this kind of 2-way binding with view-model properties.
All these patterns are based on the fantastic MV* pattern. It was originally called the MVC design pattern. So this is the exact same pattern as Asp.Net MVC then? Actually, not quite. Controller means something completely different to start with (see MVC on wikipedia). The original MVC controller handles all user input directly not via the view. Second, the original MVC pattern was designed for a desktop app GUI and Asp.Net MVC adapted the pattern for use in a client-server web app. An ASP.Net controller is a collection of http end-points which the client-side html page can hit (eg form-post, page-navigation, ajax).
So there are a lot of M-something-V patterns and the general pattern is often called the MVC design pattern.
There's one more important wrinkle: client-side vs server-side. We've introduced rich client-side javascript frameworks and the fantastic MV* pattern is great here too. So now we could have something like: client-side View-Model-ServerHTTPEndPoints and server-side ServerHTTPEndPoints-ServerModel. The server-endpoints refers to Asp.Net controllers or the equivalent in whatever web framework or programming language you are using. From the server-side point of view, the entire client-side html is the view. The client-side model talks to the server ajax api (http endpoints) to sync data or trigger advanced actions. The ServerModel is normally a database. In knockout/vue, instead of client-side "Model", it would be ViewModel. If you use react/vue with redux/flux then the client-side would be View-ViewModel-Model-ServerHTTPEndPoints where the Model would be the redux/flux Stores. Also, often on the server-side, a service is introduced: ServerHTTPEndPoints-Service-Model. This way unit tests can hit the service directly rather than firing up the entire web server and making HTTP connections.
I have used MVVM in desktop applications and I have a property in my viewmodels named Model where I store a business object as the model. My views have a property named DataContext where the viewmodels are stored before the views are loaded. A view bind its controls to the business object using the path DataContext.Model.BusObjPropertyName. I have a UserInteractionService that register from the start the relationships between views and viewmodels. When a viewmodel needs to show another viewmodel, it calls the method ShowView in the UserInteractionService and pass the viewmodel as parameter. Then the service instantiate the view corresponding to the viewmodel received, set its DataContext property with the viewmodel and show it.
If it is possible to do the bindings to a path like that above in Asp, all this model can be reused either in desktop as in Web applications.

How do viewModels fit into WebApi implementations with ASP .NET MVC?

Right now I have a few layers to my project: Core <> Repository <> API... and I'll be building a "client" MVC web project layer. My question is - where do viewModels belong in this architecture?
Should the controller methods of the Web Project call the API (multiple times - getTheseObjects, getThoseObjects) to get data, and then build the viewModel? Or should the API support calls to construct the viewModel so that only one API call (getAllObjectsForThisPage) needs to be made per page for the application?
Your view models will belong in your client MVC app. They will be specific to the views in that individual client application, and usually will get populated by domain objects.
This is how it can work: the controller mediates the https requests thus calls a API endpoint and receives some data or domain objects, which in turn you use to populate your view models.
Take a look at automapper if you are returning domain objects from your api, it really helps with mapping domain object to view models.
You can place ViewModels into your MVC application, but you could create something that is called DTO (Data Transformation Object) and return that from Web API to your client. In essence it will be a class with only the necessary information that you pass to the client. If you want to call that ViewModel you might as well go ahead and call it like that. My suggestion would be to issue one call and to return all the necessary information. One call one trip.
My practice usually is to separate ViewModel from MVC and store it in some other project. The service layer would prepare a ViewModel and return it to MVC. The reason for this is that once I had a requirement to build WPF application after MVC was completed. It was quite a pain moving things around and retesting everything to make sure that it still works fine.

Is it a good practice to use an MVC application's own Web API for Ajax bindings?

I'm writting an application that has many Ajax widgets (Kendo-UI to be percise). It's starting to get messy to have all those Ajax responses without the standard controllers so I was starting to consider making each entities their own controller. If I'm taking the time to do this, I figured I might as well go foward and do those as WebAPIs since I was planning to do this in a not so close future, but hey, it would be done already...
So my question is: Is it a good practice to use an MVC application's own Web API as a Ajax Widget feeds or is there any reason to stick with standard Controllers?
I've seen some arguments about performance, but I don't think this applies to this situation. I believe it was more of a "Controller calling WebAPI" situation which has obvious performance hits. But since it's already a client side Ajax call, weither it goes into a standard MVC Controller or a WebAPI controller shouldn't change a thing, would it?
Edit
Additional information regarding the project:
I am using Entity Framework for the data access.
I have a repository pattern going on with UnitOfWork.
I am using proper a MVC structure (EF POCOs AutoMapped to DTO POCOs in the repository and fed into View Models by the controllers)
This is a MVC 4 project on .NET 4.0
There is a lot of database relationships (specially for the object I'm working with at the moment)
I don't know about "good practice", but it's certainly not "bad practice". I see no difference whether you do it in the app or a different one.
I think its a good thing but only if what you are doing in the API is kept as generic as possible to other applications and services can reuse the API.
Both the applications I have written and continue to maintain use pretty much the exact same stack as your app.
I have recently re-factored one of the applications to use the API for all the common things like lists that I'm binding to Kendo ComboBoxes etc. in my views. Its a fairly large application that re-uses a lot of the same lists such as states, priorities, complexities across various Entities and views so it makes sense to put those in the API.
I haven't gone as far as going the whole hog through. I draw the line with things like this:
public ActionResult GetAjaxProjectsList([DataSourceRequest]DataSourceRequest request)
{
return Json((DataSourceResult)GetProjectsList().ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
}
That is very specific to how the Kendo Grid wants the data back. Nothing else I have connecting to this app will use this data in this format so I keep it in the controller.
In short... I use the API for common things within the same MVC app and things that I allow to be used by other applications or services, like Excel.

Resources