MVC Service layer validation within WebForms application - asp.net-mvc

We have a service layer within our MVC3 application using an almost identical approach as described here: http://www.asp.net/mvc/tutorials/older-versions/models-(data)/validating-with-a-service-layer-cs
The service layer doesn't depend on MVC.
The issue is we have a legacy webforms application that needs to also create these services and I'm trying to come up with the best approach on how to instantiate these services. It would also be nice to have the Validate() method return the validation errors.
An individual service requires an IValidationDictionary at construction which within our MVC app we simply use the ModelStateWrapper(this.modelstate) however in Webforms we obviously don't have the concept of ModelState (as in Controller.ModelState)
So my question would be how would you construct a service layer with model validation that can be used within an MVC and Webforms application?
At this stage we're not considering an IoC
On a side note:
Am I missing something obvious with ModelStateDictionary? It's within the MVC namespace but doesn't appear to be dependant on the MVC framework? Isn't it just a wrapper for a Dictionary with a setup?

The ModelStateWrapper is a good approach for MVC but like it's an implementation of the IValidationDictionary. You could do a web form implementation but instead use a validation summary control instead of the model state.
Sorry I don't have any code to show you at this time.

Related

What is the difference between MVC in Angular JS and MVC in ASP.NET or Spring MVC?

I'm trying to understand modern web applications architecture. In ASP.NET MVC, all the business logic classes are in Model and Controller takes and guides user requests.If I am using it, is it possible to use Angular JS which itself is a MVC architecture but all the business logic is in controller and model is just POJO.
Can Angular JS be used only with Web API 2 where it gets data from a RESTful service and it does all manipulation on the client side? Which architecture is most commonly used ?
From my perspective, you're confusing two very different technologies; One is server-side (ASP.NET MVC) an one is Client Side (AngularJS).
The two can certainly be used hand-in-hand as neither are dependent on the other existing. And, IIRC, there is a scaffolding module on NuGet that helps bindings from one to the other (Create JS objects from your ASP.NET POCO objects).
With that being said, there is no reason you need to use both. You can one one or ther other, both, or bring in a different technology altogether (KnockoutJS, etc.)?
In ASP.NET MVC, all the business logic classes are in Model and Controller takes and guides user requests
This is not true. Models (a.k.a. ViewModels) should be plain ("POCO") data containers in ASP.NET MVC. Business logic should come from a layer consumed by the controllers, but in smaller applications or before refactoring, the controller is a more appropriate choice than a (View)Model.
Can Angular JS be used only with Web API 2 where it gets data from a RESTful service and it does all manipulation on the client side? Which architecture is most commonly used?
No, you can use ASP.NET MVC with Angular JS as well by returning JsonResults from controller actions. That said, WebAPI is a better / more appropriate choice. Of course you can also use Angular with many other non-Microsoft tools that return JSON over http(s) (for example node, ruby, java, etc).
To more directly answer your actual question, the main difference between the two is that one is an MVC pattern for the server, and the other is an MVC pattern for the browser. Angular actually likes to call it an "MVW" pattern, where the "W" stands for "Whatever".
Like as other design patterns (Singleton, Factory, Factory method) MVC
is also a design pattern that we can use in any technology like(Java,
.net, PHP) or to any client site scripting. there is no difference between MVC in Angular JS and MVC in ASP.NET and Spring MVc

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.

Unifying MVC (3) with Winforms

I've created a business/data architecture that I'm happy with, and I'm presenting it in Winforms in a fairly standard way by having a controller consume a service and bind the result to a Winforms Datasource. Now, I want to expose my architecture through MVC 3, and I'm looking for guidance on how to avoid duplicating all my controller classes. I'm a little thrown by Controller and ViewResult not simply implementing interfaces that I can apply to my existing controller classes and plug into web views. Ideas?
ASP.NET MVC uses front controller architecture, which provides entry point for handling web requests. This controller is coupled with web environment (HttpContext, Request, Response, etc), and it returns view, instead of updating existing one. Thus you can't and should not use it in WinForms development. What you should reuse is model, which is environment independent and does not know anything about controllers or views.

How ASP .NET MVC architecture fits into the traditional multi layered architecture

Moving from the traditional way of architecting web applications with a Business Layer, Service Layer, Data Access Layer and a Presentation Layer to the MVC design pattern, I find it difficult to understand how it fits in the old model.
It seems to be that the MVC model itself already has done allot of the separation of concerns that is needed and used to be achieved via a layered architecture. Can someone shed some light on this subject please?
As a reference, below is how I understand it, please share your view on this
MVC Views and Controllers along with View Models -are- Presentation Layer
MVC Models - could be - Data Access Layer or Business Layer or even Service Layer
I see the Asp.Net MVC part only as the view (or presentation) part of the whole application.
I struggled too with the problem how to structure the app in a proper way.
Following the Onion Architecture I heard about here (and especially the image found here), my solution looks this way:
Project.Core
Business logic/services implementations, entities, interfaces that must be implemented by the other projects (i.e. "IRepository", "IAuthenticationService",...)
Project.Data
DB connection - in my case NHibernate repositories and entity-mappings go here.
Implements data-interfaces of Project.Core
Project.UI.Web
The Asp.Net MVC ("presentation") project - it wires the whole app together.
Has implementations for Interfaces in Project.Core and wires them (and those from Project.Data) up with some DI framework like Castle Windsor.
Project.UI.Web follows the following conventions:
its models are only(!) viewmodels
the views consume their own viewmodel (one-view-one-viewmodel)
the controllers just need to validate the input, transforms it into domain objects (as the business logic knows exacly nothing about viewmodels) and delegate the real work (business logic) to the business services.
Summary:
If you follow this model it's helpful to focus on Project.Core: that is the real application. It doesn't worry about the real persistence of data nor cares about how does it get presented. It's just about "how-to-do-it". But it's laying out the rules and contracts (interfaces) the other projects must provide implementations for.
I hope this helps you with how to layout an Asp.Net MVC application!
Lg
warappa
As others have said, it doesn't change much. My apps are typically architected as such:
Model Layer (Domain and View Models)
Repository Layer (data access)
Service Layer (sometimes implemented
as WCF services depending on the
app/requirements)
Server side MVC
Layer (Asp.net MVC itself)
Client side MVVM or MVC (via
either Knockout.js, Backbone.js, or
Spine.js)
In the server side MVC layer, my controller methods are very light. They typically call a method on a service layer object to get some data and pass it along to the client as Json data.
Because I'm sending Json back, my views are also very light and sparse. Typically just containing script includes and templates which will be rendered with a client side templating library.
In short: nothing much changes.
I'm only familiar with a few presentation patterns: MVP (Model, View, Presenter, common in windows forms/asp.net), MVC (Model, View, Controller) and MVVM (Model, View, View Model, commonly used in WPF/Silverlight).
Link: http://haacked.com/archive/2008/06/16/everything-you-wanted-to-know-about-mvc-and-mvp-but.aspx
Above link should answer some (if not all) of your questions.
The way I usually write ASP.NET MVC applications is by including at least a Service/Business layer hybrid for CRUD operations (because data access belongs neither on the view model or controller and definitely not in the view!).
Very basic explanation:
If you create a new MVC application you will automatically get a Controllers, Models and Views folder.
Your controllers act like your Business Layer
Models are Data Access/Service layer
and Views are the presentation layer.
See http://www.asp.net/mvc for a fully detailed explanation.

What Is ASP.Net MVC?

When I first heard about StackOverflow, and heard that it was being built in ASP.Net MVC, I was a little confused. I thought ASP.Net was always an example of an MVC architecture. You have the .aspx page that provides the view, the .aspx.vb page that provides the controller, and you can create another class to be the model. The process for using MVC in ASP.Net is described in this Microsoft article.
So my question is. What Does ASP.Net MVC provide that you wouldn't be able to do with regular ASP.Net (even as far back as ASP.Net 1.1)? It is just fancy URLs? Is it just for bragging rights for MS to be able to compare themselves with new technologies like Ruby On Rails, and say, "We can do that too"? Is there something more that ASP.Net MVC actually provides, rather than a couple extra templates in the File->New menu?
I'm probably sounding really skeptical and negative right now, so I'll just stop. But I really want to know what ASP.Net MVC actually provides. Also, if anybody can tell me why it's Model-View-Controller and not in order of the layers of View-Controller-Model or Model-Control-View depending on whether you are going top to bottom, or vice versa, I'd really appreciate that too.
EDIT
Also, it's probably worth pointing out that I've never really cared for the web forms (AKA server controls) model either. I've only used it minimally, and never on the job.
.aspx doesn't fulfill the MVC pattern because the aspx page (the 'view') is called before the code behind (the 'controller').
This means that the controller has a 'hard dependency' on the view, which is very much against MVC principles.
One of the core benefits of MVC is that it allows you to test your controller (which contains a lot of logic) without instantiating a real view. You simply can't do this in the .aspx world.
Testing the controller all by itself is much faster than having to instantiate an entire asp.net pipeline (application, request, response, view state, session state etc).
Scott Guthrie explained it in this post "ASP.NET MVC Framework"
It enables clean separation of concerns, testability, and TDD by
default. All core contracts within
the MVC framework are interface based
and easily mockable (it includes
interface based
IHttpRequest/IHttpResponse
intrinsics). You can unit test the
application without having to run the
Controllers within an ASP.NET process
(making unit testing fast). You can
use any unit testing framework you
want to-do this testing (including
NUnit, MBUnit, MS Test, etc).
It is highly extensible and pluggable. Everything in the MVC
framework is designed so that it can
be easily replaced/customized (for
example: you can optionally plug-in
your own view engine, routing policy,
parameter serialization, etc). It
also supports using existing
dependency injection and IOC container
models (Windsor, Spring.Net,
NHibernate, etc).
It includes a very powerful URL mapping component that enables you to
build applications with clean URLs.
URLs do not need to have extensions
within them, and are designed to
easily support SEO and REST-friendly
naming patterns. For example, I could
easily map the /products/edit/4 URL to
the "Edit" action of the
ProductsController class in my project
above, or map the
/Blogs/scottgu/10-10-2007/SomeTopic/
URL to a "DisplayPost" action of a
BlogEngineController class.
The MVC framework supports using the existing ASP.NET .ASPX, .ASCX, and
.Master markup files as "view
templates" (meaning you can easily use
existing ASP.NET features like nested
master pages, <%= %> snippets,
declarative server controls,
templates, data-binding, localization,
etc). It does not, however, use the
existing post-back model for
interactions back to the server.
Instead, you'll route all end-user
interactions to a Controller class
instead - which helps ensure clean
separation of concerns and testability
(it also means no viewstate or page
lifecycle with MVC based views).
The ASP.NET MVC framework fully supports existing ASP.NET features
like forms/windows authentication, URL
authorization, membership/roles,
output and data caching,
session/profile state management,
health monitoring, configuration
system, the provider architecture,
etc.
Primarily, it makes it very easy to create testable websites with well defined separations of responsibility. Its also much easier to create valid XHTML UIs using the new MVC framework.
I've used the 2nd CTP (I think they're on five now) to start work on a website and, having created a few web applications before, I have to say its hundreds of times better than using the server control model.
Server controls are fine when you don't know what you're doing. As you start to learn about how web applications should function, you start fighting them. Eventually, you have to write your own to get past the shortcomings of current controls. Its at this point where the MVC starts to shine. And that's not even considering the testability of your website...
No more auto-generated html IDs!!! Anyone doing any sort of javascript appreciates this fact.
ASP.Net with it's code behind is almost MVC - but not - the one big thing that makes it not is that the codebehinds are tied directly to the aspx's - which is a big component of MVC. If you are thinking of the codebehinds as the controller - the should be completely decoupled from the view. The new .NET MVC rounds this out - and brings a complete MVC framework. Though there are existing ones for .NET already (see Spring.NET).
I looked through a couple simple examples such as this one. I can kind of see the difference. However, I don't really see how MVC uncouples the view from the controller. The view still references stuff that's in the controller. I do see how it makes it much easier to test, and that at least in MVC the controller doesn't have any knowledge of the view. And you wouldn't have to process the view to call methods in the controller. I can see that's quite a leap, even though at first glance it may not seem like much.
I do agree with #Will about fighting server controls. I've never worked in a situation where they were actually used, but many people I know who have, have run into quite a few limitations with them.
Article about ASP.net MVC Vs ASP.net Web form
http://weblogs.asp.net/shijuvarghese/archive/2008/07/09/asp-net-mvc-vs-asp-net-web-form.aspx

Resources