ASP.NET MVC 3 Unobtrusive client side Validation - asp.net-mvc

Is there a reference available of the html validation attributes for cases where we want to use unobtrusive client side validation without using Data Annotations?
Thanks,
Ben

I don't think you will find a reference for this but if you are not going to use Data Annotations I would simply recommend you hooking up the jquery validate plugin manually.

We unfortunately had to do this recently, since only the view was under our control. Since the unobtrusive validation is really meant to be used in conjunction with data annotations, you probably won't find documentation online for how to use them separately.
We found that the easiest thing to do was to create a spike project, and add the correct data annotations to some test model, create a simple "EditorFor" view for it, look at the generated HTML, and copy over the data attributes that ASP.NET MVC added to the text boxes.

Related

Angular with .NET WebAPI validation, and single-point-of-truth

Is there an approach that preserves the single-definition of validation, allows immediate client-side validation, and still provides the strength of server-side validation?
I'm familiar with the following two approaches:
ngval (https://github.com/alisabzevari/ngval)
http://www.danielroot.info/2013/09/hooking-angularjs-validation-to-aspnet.html
The first renders ng-validation syntax in Razor output, based on rules stated in the model. That seems like it couples me too tightly to building Razor views, when Razor views often won't intuitively pair with a well-organized Angular app. I could use this approach, but it seems it's more a result of someone wanting to replicate "Unobtrusive jQuery/MVC Validation", than building something well-suited to Angular.
The second approach just returns server-side validation back to Angular to render. It also doesn't do a thorough job of it. If needed I could run without client-side validation, since a single-page app still won't get screen flashes... but it's not ideal.
For example, maybe there is a toolset to more directly reflect the validation rules directly on WebAPIs and consume them in an Angular app. Or another approach that I haven't found?
At https://www.youtube.com/watch?v=lHbWRFpbma4#t=1336 , the presenter seems to imply this problem is already well-solved for Angular, and refers to specification (DDD Using Specification pattern for Validation). If you are aware of any tools that make this applicable to my problem, I'd love to hear it.
p.s. It seems like this is almost certainly an often-asked question. I'm sorry I was unable to find an answer here before posting
p.p.s. I'm currently planning to use Entity Framework, but I'd switch to address this. Heck, I'd consider switching to a whole different platform for this, my first Angular-focused project.
The approach I recommend is based on #Esteban Felix commented and I used similar strategy in Java/Bean Validation and JSON schema generator.
Annotate your Domain model using Validate Model Data Using DataAnnotations
Generate schema using JSON.net other useful links
Create a AutoValidate directive that goes on and decorate fields with AngularJS build in directives for form validation e.g. ngPattern and simple things like min/max. In my case I created a mapping from Java world to AngularJS directives and wherever I needed we created custom directives.

Razor templates, views and angular.js

TL;DR
What are the best practices when using .NET Razor views and AngularJS?
Context
We are developing a public website (not an intranet application) using mvc4 with razor, and we weren't very familiar with client script, so we started with what we knew: jQuery.
But now things are getting more complicated and we'd like to switch to AngularJS.
On the .NET part, we use Razor templates and UIHintAttribute (plus some custom ones) to render the right html "control". We also add custom html attributes to give extra information to the jQuery part (like title for a tooltip....)
So we already use a declarative way of setting the user interface behavior, that's why AngularJS seems a good option.
Questions
Since we already have models defined server side, and since AngularJS also uses models, wouldn't it force us to duplicate code?
How do we deal with data binding feature, since we already do some binding server side (in the views). Should we make a completely asynchronous application, making AJAX calls from AngularJS to load data, or can we mix both?
Anything else we should be aware of when trying to use both of these technologies?
I did some research on Google, but I can't find detailed ways of mixing Razor views and templates with AngularJS... Perhaps that's just not a good thing to do?
We dealt with this issue for months when working with MVC plus another JavaScript framework (Knockout). Ultimately, if you're going to be using a client-side MV* framework for rendering your user interface, you will find that mostly ditching Razor is going to be your best bet.
Most of the major MV* JavaScript frameworks, including AngularJS, assume you will be maintaining UI state and rendering your user interface based on JavaScript models or view models. Trying to mix in server-side rendering is just not going to work very well.
That's not to say there is no use for MVC when it comes to developing an Angular application. You can still take advantage of some great features like ASP.NET Bundling and Minification. And sometimes it works really well to embed JSON directly into the page using a Razor view or partial as opposed to making an additional AJAX call.
As for models, you may want to take a look at Breeze.js. It's a JavaScript library for data access that goes great with ASP.NET on the server side to share model metadata.
We wrote our own data binding mechanism that synchronizes the angular.js model with a view model on the server side. The javascript model is generated from a JSON serialization of the server-side view model to avoid the duplicate code that you were talking about.
We are using SignalR to update the client's view model from the server.
Server-side changes of the C# view model properties are sent to the client as a packet containing the path to the property, e.g. Persons[42].Address.City, and the value itself, e.g. New York. The view model inherits a base class that takes care of generating the property path, so the actual view model looks quite clean and we can concentrate on business logic.
Client-side changes of the javascript view model properties are sent to the server in the same way. To catch the change events, we encapsulate all fields of the original javascript model in get/set properties where the setter sends the update packet to the server.
Server-side methods of the view model can be invoked in a similar way. All objects in the view model have an invokeMethod function that can be used like this: Products[42].Manufacturer.invokeMethod('SendEmail', 'mailsubject', 'mailbody'). This will send a packet to the server containing the method path Products[42].Manufacturer.SendEmail and the arguments as an array of ['mailsubject','mailbody'].
In conclusion, the html view (kind of) binds to the view model on the server side where other systems, such as regular Razor views can work on the same objects.
The source code can be found here: SharpAngie.

ASP.NET MVC inserting form values into a ViewModel

I'm trying to work out if there's a built in way in ASP.NET MVC to assign the form values that are POST'd back to the properties of the ViewModel that was originally sent to the View?
So I'm thinking along the ideas of decorating some of the properties in the ViewModel with an attribute and then reflecting over the ViewModel and using that name to extract values (and coerce) from the Form[] object.
However, I'd imagine that something like this was already built in and so don't want to re-invent the wheel here.
The problem that I'm trying to solve is that a user clicks a button on a form and the server validates the data and if there are errors we return the user to the form by using the same ViewModel to carry the data and thereby fill the values back into the form that the user originally entered.
(Yes, I'm also doing client side validation using JavaScript to make this lightweight but for security I have to repeat validation on the server.)
Ideas?
You can use UpdateModel or TryUpdateModel in your controller.
I recommend using one of the overloads in which you specify the fields to be updated.
This is discussed in detail on page 78 of the Wrox Professional ASP.net ebook (or echapter!)
I don't think MVC has anything like this built in, or at least I haven't seen anything. It would be nice though as many other MVC frameworks do this (struts for example).

Options for asp.net MVC Validation Framework

I'm thinking of two options right now for model-base validation for an ASP.net project I'm starting:
xVal (Steve Sanderson's project) and the Enterprise module that Stephen Walther uses on this page
I don't really know enough to talk about the preferences as I haven't used either of them yet. Any ideas?
Update Using LinqToSql for ORM right now, but am open to changes.
One difference I see in reviewing the two is that Stephen Walther's blog post describes a library which does only validation in the Web server, where as xVal works with jQuery validators to do in-browser validation, as well. This feature, incidentally, is almost completely automatic.
FluentValidation is nice. NHibernate also has built in model validation. Then you need something like Scott Guthrie's technique for binding errors to the UI.
I've been using xVal to and i have integrated it into the IDataErrorInfo interface introduced into MVC RC1. I like it.
Here is a post I wrote which explains a few things.
http://schotime.net/blog/index.php/2009/03/05/validation-with-aspnet-mvc-xval-idataerrorinfo/
Hope this helps.
Shamelessly promote my validation library. Built for jQuery validate & Enterprise Library and work out of the box for just that. That said, functionality and code are simple enough to modify/extend if you want.
You could also check out this new technique on LosTechies http://www.lostechies.com/blogs/hex/archive/2009/06/10/opinionated-input-builders-for-asp-net-mvc-part-5-the-required-input.aspx I like the fact that you inputs are setup globaly which is really DRY. Also you could just skip the client side validation and do an jquery ajax submit form to the server, which performs validation model and business logic all in one place, which is also DRY :) Also it means you will get the product out the door quicker and you can add client side validation later as a bonus or to progressively enhance the forms.
Another vote for xVal. It's real sweet. I like using Buddy Classes and DataAnnotations to do the validation lifting. Outside of making things work with Linq2Sql as you cannot add attributes to your fields, buddy classes give one a bit of flexibility to have multiple models share the same validation info. Comes in real handy for those ModelEditData classes that seem to always become neccessary.
Are you using an ORM? If so, which one are you using? I've had a lot of luck, when using Castle ActiveRecord, simply sticking with their default model-level validation. If you're not using that, though, this is probably not too helpful. :-)

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