Using ViewModel in ASP.NET MVC with FluentValidation - asp.net-mvc

I am using ASP.NET MVC with Entity Framework POCO classes and the FluentValidation framework. It is working well, and the validation is happening as it should (as if I were using DataAnnotations). I have even gotten client-side validation working. And I'm pretty pleased with it.
Since this is a test application I am writing just to see if I can get new technologies working together (and learn them along the way), I am now ready to experiment with using ViewModels instead of just passing the actual Model to the view. I'm planning on using something like AutoMapper in my service to do the mapping back and forth from Model to ViewModel but I have a question first.
How is this going to affect my validation? Should my validation classes (written using FluentValidation) be written against the ViewModel instead of the Model? Or does it need to happen in both places? One of the big deals about DataAnnotations (and FluentValidation) was that you could have validation in one place that would work "everywhere". And it fulfills that promise (mostly), but if I start using ViewModels, don't I lose that ability and have to go back to putting validation in two places?
Or am I just thinking about it wrong?

Or am I just thinking about it wrong?
Probably ;)
If you add all the validation code to your ViewModels you'd just be validating them instead of your actual Models. All your really changing is which objects can enter an invalid state.
Right now I'm happy as pie only validating ViewModels and then passing that information back to the actual Models and DAO layers. Whether or not your domain can enter an invalid state is a contentious topic though but so far this technique is working great for me. Validation in one place and no invalid objects in my persistence store.

Related

Any tool to autogenerate View Models from Entity Framework Domain Models?

I am using MVC3, ASP.NET 4.5, C#, MSSQL.
I need to create ViewModels from my Domain Model that is automatically generated by Entity Developer.
Once I create the relevant ViewModel for an entity I can comment out non required properties for a particular View.
However there is the ongoing concern that once an entity is upgraded then the ViewModel could become out of sync, and I want to minimise the risk/effort in fixing this.
Thanks in advance.
I see the same complaint endlessly about using view models. True, they can be repetitive in nature, but copy and paste works beautifully there. If you so wanted, you could even design an interface that both your model and view model must implement, which can help you keep the two in sync somewhat. However, I think you'll find that the two will diverge more than you think.
As far as validation goes, this is also a common complaint, but it's actually a symptom of bad design. Your entity class should only have validation specific to the database, which you'll find is actually pretty sparse. Entity Framework actually does a fantastic job translating most of the properties inherent limitations to the database. For example, a DateTime property's column is set as NOT NULL by default, because the C# type itself cannot be null. There's no need to add something like [Required], because the behavior is inherent.
Other types of validations such as regex are totally inappropriate for a domain model because there's no correlation to anything happening at the database level. It's entirely for the UI, and thus belongs on your view model. I think you'll find that if you evaluate all the things you're trying to validate on your domain model, you'll find most if not all should be strictly on your view model(s) instead.

ASP.NET MVC with Knockout and Web API: does it make sense?

does it make sense to use KnockoutJS Viewmodels in combination with ASP.NET MVC3 or 4? Because it is not very DRY, isn't it? I have to write models for EF, Viewmodels for the MVC Views and Viewmodels for Knockout... and i lose a lot of magic. Automatic client-side validations for example.
Does it make sense to use MVC at all if one sticks with the MVVM Pattern?
With Knockout Mapping, you can automatically generate a KO view model from your MVC view model.
This is a proper pattern: your models are raw entities, your data. Your views are the UI. And your view models are your models adapted to that specific view.
This may be an unpopular answer, but I don't use ko.mapping to translate my C# POCOs into JS viewmodels. Two reasons, really.
The first is a lack of control. ko.mapping will turn everything into an observable if you let it. This can result in a lot of overhead for fields that just don't need to be observable.
Second reason is about extensibility. Sure, ko.mapping may translate my C# POCOS into JS objects with observable properties. That's fine until the point you want a JS method, which at some point, you invariably will.
In a previous project, I was actually adding extra methods to ko.mapped objects programmatically. At that point, I questioned whether ko.mapping was really creating more problems than it solves.
I take on board your DRY concerns, but then, I have different domain-focused versions of my POCOs anyway. For example a MyProject.Users.User object served up by a UserController might be very different from a MyProject.Articles.User. The user in the Users namespace might contain a lot of stuff that is related to user administration. The User object in the Articles namespace might just be a simple lookup to indicate the author of an article. I don't see this approach as a violation of the DRY principle; rather a means of looking at the same concept in two different ways.
It's more upfront work, but it means I have problem-specific representations of User that do not pollute each others' implementations.
And so it is with Javascript view models. They are not C# POCOs. They're a specific take on a concept suited to a specific purpose; holding and operating on client side data. While ko.mapping will initially give you what seems to be a productivity boost, I think it is better to hand-craft specific view-models designed for the client.
btw, I use exactly the same MVC3/KnockoutJS strategy as yourself.
We use knockout Mapping to generate the KO view models well.
We have a business layer in a separate project that does CRUD, reporting, caching, and some extra "business logic". We aren't going to be using EF, or something similar. Currently we've defined c# classes as MVC models, and our controllers call the business layer to construct the Models that are defined in the usual place in our MVC app. These C# models get serialized as JSON for use in our pages.
Since everything we do in the browser is c#/JSON based using knockout, we aren't using MVC models in the traditional MVC way - everything gets posted as JSON and serialized to c#, so we don't use MVC model binding, validation, etc. We're considering moving these models to our business layer so they can be tested independently of the web app.
Se we'll be left with an MVC app that has controllers and views, but no models - controllers will get models that are defined in the business layer. We're nervous about departing from the normal MVC structure, but a KO/javascript based client is fundamentally different from a DOM based client that MVC was originally built around.
Does this sound like a viable way to go?
I work now on project which mixes MVC3 and knockouts and I have to tell you - it's a mess...
IMO it's nonsense to force some patterns just to be up to date with trend.
This is an old topic, but now in 2014 (unfortunately) I still feel this question has a huge relevance.
I'm currently working on a project which mixes MVC4 with knockoutjs. I had some difficoulties to find whichs part should be handled on which side. Also, we needed a "SPA-ish" kind of architecture, where each module has its own page, but then inside that module there is only AJAX interaction. Also faced some heavy validation scenarios, and needed to provide user (and SEO) friendly URLs inside each module. I ended up with the following concept, which seems to be working well:
Basic MVC and .NET side roles:
Handling authentication and other security stuff.
Implementing the Web API interface for the client-side calls (setting up viewmodels, retrieving and mapping data from the domain, etc.)
Generating knockout viewmodels from my (pre-existing) C# viewmodels with T4 templates, also including knockout validation plugin extensions from .NET validation attributes. (This was inspired by this aticle). The generated viewmodels are easily extensible, and the generation can be finetuned with several "data annotation"-like custom or built-in attributes (such as DefaultValue, Browsable, DataType, DisplayFormat, etc.). This way the DRY doesn't get violated (too much).
Providing strongly typed, but data-independent partial view templates for each submodule (each knockout viewmodel). Because property names on C# viewmodels are same as in KO models, I can benefit from the strongly typed helpers specifically written for KO bindings, etc.
Providing the main view for each module similarly to previous point.
Bundling and minification of all scripts and stylesheets.
Basic client-side roles:
Loading the initial state of all viewmodels encapsulated into one module page, taking the whole URL into account with a simple route parser implementation.
Handling history with history.js
Data-binding, user interaction handling.
Posting relevant parts of viewmodels to the server, and processing the returned data (usually updating some viewmodel with it).
I hope this could help anyone else who feels lost in the world of trendy technologies. Please, if anyone has any thought on this, feel free to post any question or suggestion in the comments.

Fluent Validation, Domain and ViewModels

I've been developing a web application with asp.net mvc, nhibernate and ddd concepts.
I've developed validations with Fluent Validation for my domain classes and it works fine. Well, now, I need a ViewModel to edit an entity in a View, soo, my question is, Do I need to create another validation class to validate my viewmodel? Or what should I do to get around this situation?
I ask it because I don't want to broke the DRY (don't repeat yourself) concetp.
Thanks!
Domain level validation, and View-Model validation are quite different imho (although they can have lots of overlap).
For instance, it may be perfectly allowable to have a certain field as null in your database, but require it's input on certain webforms. In this case you would check for null within the Model validation.
It would also be quite normal for multiple client applications to share the same Domain controllers (via WCF for example), but to possess different application validation logic.
If you use DataAnnotations in your view model you can get client-side javascript validation for free, so as a general rule, I always have a separate ViewModel from my Domain objects, even if it's a 1:1 mapping - I just use AutoMapper to translate between them. In addition to getting the client-side validation, it also reduces the clutter within the Domain validation.

Proper way to validate model in ASP.NET MVC 2 and ViewModel apporach

I am writing an ASP.NET MVC 2 application using NHibernate and repository pattern. I have an assembly that contains my model (business entities), moreover in my web project I want to use flattened objects (possibly with additional properties/logic) as ViewModels.
These VMs contain UI-specific metadata (eg. DisplayAttribute used by Html.LabelFor() method).
The problem is that I don't know how to implement validation so that I don't repeat myself throughout various tiers (specifically validation rules are written once in Model and propagated to ViewModel).
I am using DataAnnotations on my ViewModel but this means no validation rules are imposed on the Model itself. One approach I am considering is deriving ViewModel objects from business entities adding new properties/overriding old ones, thus preserving validation metadata between the two however this is an ugly workaround.
I have seen Automapper project which helps to map properties, but I am not sure if it can handle ASP.NET MVC 2 validation metadata properly. Is it difficult to use custom validation framework in asp.net mvc 2?
Do you have any patterns that help to preserve DRY in regard to validation?
It is fine to repeat validation. Trick is to place it where it's appropriate.
In your case - at UI, validate UI logic (view model props must not be null, in correct format etc.), in business layer - validate business logic (account has money etc.).
Do not use DRY as an excuse to violate SRP! :P
View models are supposed to uncouple your business layer from presentation role.
Don't glue everything together again.
I guess Automapper can't handle that. :)

Which validation library for ASP.NET MVC?

I'm trying to decide what validation approach to take for a new ASP.NET MVC project. (And wow there are plenty of options!)
The project uses NHibernate, so the first thing I considered was the NHibernate Validator (Because of tight integration with NHibernate). However, as far as I can see there are only a couple of benefits to this tight integration:
1) DB Schemas generated by NHibernate will include details of validation (e.g. column lengths will be set to max value allowed in validation). (This is not really of interest to me though, as I generate schemas manually.)
2) NHibernate will throw an exception if you try to save data that doesn't meet the validation specs. (This seems fairly redundant to me, since the data presumably will already be validated by whatever mechanism you choose before saving anyway)
If there are more benefits to NHibernate Validator please let me know!
Other libraries which I've been reading a little about include:
MS DataAnnotations
Castle Validator
Something else?
I've also been thinking about using xVal to provide client side validation from the same set of rules. However, I hear that ASP.NET MVC v2 will include something similar to xVal (integration with jquery) out of the box? Will this new included functionality render some of the others redundant?
So, I'm basically asking for people's advice on which direction to take here. I don't want to implement a particular scheme, only to have to rip it out when another one becomes the dominant tech.
What has worked for you? Which option do you think has/will have the edge?
Thanks!
I have been using FluentValidation along with jQuery validation plugin and still cannot find a situation they cannot handle.
I like xVal.
You can implement very easily client and server validation with it. Also there is support for column (property) validation on entities that you would like to use.
DataAnnotations implemented by buddy classes and JQuery client validation
Make sure you're using MVC Preview 2
You might be interested in this delegate approach. I was because i didn't like the xVal idea (the solution im currently going with) and the fact that it didn't seem to cater for complex validation cases that crossed multiple properties of the same or even different class structures.

Resources