Knockout + mvc 3 + Validation - asp.net-mvc

In the controller I would like to be able to get to the client validation rules of the model. I've attached some attributes using data annotations and would like to be able to pass something back to the client via the ajax call so I can then build the jquery validate options automatically.
Normally this is done for free with the unobtrusive stuff, but I'm trying to leverage knockout binding, while still not having to replicate the validation rules on both the server and client.
Without using reflection on the model server side I'm a little unsure on how to achieve this.

In my Mvc Controls Toolkit I developed Helpers based on the knockout library. These helpers not only help in writing the knockout code, but enhance the knockout library with Unobtrusive validation and globalization. Moreover, the binding mechanism is enhanced to include complex controls such as a DatetimePicker, and other "complex" (made by different html parts) controls.
Finally, knockout templates can be defined through Razor helpers.
See the documentation here, here, here and here. I also have some tutorials that show how to implement advanced features with my helpers:
Low BandWidth Transfers with The Client Side Templates of the Mvc Controls Toolkit
Handling Big Amounts of Data with Client-Side Templates
Handling Big Amounts of Data with Client-Side Templates 2

Depeneding on what you exactly need to do, Breeze js can be the best solution. particularly, if you're using EF, you can replicate most of the functionality of the server EF's DbContext on the client side, including, of course, the validation, but also change tracking, .saveChanges, a simple syntax that resembles LINQ queries, caching, serializing and deserializing to allow working offline, and many other things.
The basic steps to work with Breeze js are:
create an EF model in the server
add a NuGet Package on the server to create Web API Services that expose the model to the client side. This is done with a surpringly low number of C# code. One of the things that this does is exposing the metadata: definition of objects, relations, and extra information, like data annotations validation info
add a js Nuget Package for the client side which will be used to replicate the EF behavior on the client side.
Of course, not all of the functionality on the server will be replicated on the client, but you can do a lot of things:
create new entities on the client side
make queries on the client side, which will be executed on the server and returned to the client
modify entities on the client: create, modify, delete...
create relations on the client side: for example create new chlid entities in a parent object
call saveChanges on the client side, which will transfer all the tracked changes to the server so that the backend is updated
of course, while you do this, you'll get automatic client validation, and also additional server validation whenever you call .saveChanges
Finally, you can extend and modify the server code to include some business logic, so that you can do much more than simply exposing the EF model to the client.

That's quite a task. You want to be able to convert your C# code into Javascript with respective data type conversions etc. You'll be better off writing down two separate sets of validation at server and client side both. It would be a lot more easier to maintain that than to write your own conversion framework all by yourself and maintaining it

On the model use attributes validation that you like:
public class ModelWithValidation
{
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
In mvc forms
#using( Html.BeginForm())
{
#Html.TextBoxFor(m => m.Name, new {data_bind = "value: name"})
#Html.ValidationMessageFor(m => m.Name)
}
In jQuery test if form is valid onSubmit or in knockout save function call the next code to validate input. You must include jQuery.unobtrusive* and jQuery.validate* libraries. Don't forget to validate input on server side also!
var form = $("form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
$("form").valid() //true false

Related

ASP.NET MVC data-attribute with auto-bind

This is the sample ViewModel I get to the view:
public class CollectionOfStuffVM
{
public string Element { get; set; }
public bool IsPicked { get; set; }
}
This is asking for a Checkbox for multiple items, or a dropdown list if it is a single pick only.
But, what if I am drawing this in a custom way?
Eg. below (inside a editor template):
#Model.Element
All the "data-picked" stuff is being handled by javascript when something is clicked.
So, how would it be possible to automatically bind these custom "controls"?
I guess there's some work that needs to be done, i'm just not sure, where. Do I need to create a custom Input?
I know this auto bind would be doable with inputs, but i'm kinda avoding having to have hidden inputs being updated by Javascript.
Keep in mind this is just a simple example, the ViewModel is a bit more complex and it would be frustrating to have to build everything in Javascript to do an Ajax POST.
There's no such thing as two-way databinding when it comes to MVC. This is because, unlike something like a WPF application where everything runs on the same machine, a web application is disjointed, with server-side and client-side components.
If you want the data set by the client to be set back on the server, you have to post it to the server. If you handle that with a standard form, you must include some kind of input that has that value. If you do it with AJAX, you have a bit more freedom, as you don't need a physical HTML input element to hold the value, but you're still responsible for ensuring that the value makes it into the object you send to the server via AJAX.

Where do i place my viewmodel validation?

we are building an ASP.Net MVC application, and we ask ourselve the question where we shoud put the validation logic for incoming data.
We already have the simple validation in place: these are attributes on the viewmodel, like [required], [numeric] , [email] etc. (this is open for discussion too, btw)
But now we have some more input validation: we want to validate if the id's received from dropdownlists are genuine id's.
For example: when we receive 91 as a countryid, i have to make sure 91 is a valid countryid and not a value 'hacked into' the form by a user. Because if it is not a valid countryid, my datalayer generates an error.
Should i place this in the controllers action method, because that
method knows what is right and what is wrong when the data from the request arrives?
Should i place it in a VacancyValidator (the object is a Vacancy
object) where i put all validation logic for all vacancy related
viewmodels
Should i place it in the ViewModel because it should know how to validate itself
Should i create an attribute which validates the property which i place on the ViewModels property
Should i place it in a Vacancy[thisviewmodelsname]Validator where i put all validation logic for this specific viewmodel
Any ideas appreciated....
We already have the simple validation in place: these are attributes
on the viewmodel, like [required], [numeric] , [email] etc. (this is
open for discussion too, btw)
I would recommend FluentValidation.NET instead of Data Annotations which plays nicely with ASP.NET MVC. It provides a nice syntax for expressing complex validation logic between interdependent properties without writing millions of lines of plumbing infrastructure code (which is what you would have to do if you use Data Annotations and write a custom validator) and also allows you to unit test your validation logic very easily.
Because if it is not a valid countryid, my datalayer generates an error.
There you go - your data layer already handles this validation for you. But if you don't want to leave it to reach the data layer then you could have a validation rule for this property on the view model. If you follow my previous advice about FluentValidation.NET you will already know where to put this rule - in the corresponding validator of your view model.
You put your validation obviously to the view model. This way it is located in one spot (not scattered, hence DRY) and operational on both client and server.
For simple scenarios use Data Annotations.
For more sophisticated scenarios (enterprise scale etc) use Fluent Validation
Hope this helps.
The best way is to combine client and server validation. For client side validation you can use jquery validation plugin. It provides all standart validation patterns(like maxlength, minlength, required etc.).You can specify validation requirements in model attributes(data annotation) or directly in html. Also, it provides possibility for custom remote validation when validation result will be returned from server code.
But you should dublicate client side validation with server side. For example, use spring.net validation . I think it's the best generic and flexible framework.

How can I write an MVC3/4 application that can both function as a web API and a UI onto that API?

My title sums this up pretty well. My first though it to provide a few data formats, one being HTML, which I can provide and consume using the Razor view engine and MVC3 controller actions respectively. Then, maybe provide other data formats through custom view engines. I have never really worked in this area before except for very basic web services, very long ago. What are my options here? What is this Web API I see linked to MVC4?
NOTE: My main HTML app need not operate directly off the API. I would like to write the API first, driven by the requirements of a skeleton HTML client, with a very rudimentary UI, and once the API is bedded down, then write a fully featured UI client using the same services as the API but bypassing the actual data parsing and presentation API components.
I had this very same thought as soon as the first talk of the Web API was around. In short, the Web API is a new product from the MS .NET Web Stack that builds on top of WCF, OData and MVC to provide a uniform means of creating a RESTful Web API. Plenty of resources on that, so go have a Google.
Now onto the question..
The problem is that you can of course make the Web API return HTML, JSON, XML, etc - but the missing piece here is the Views/templating provided by the Razor/ASPX/insertviewenginehere. That's not really the job of an "API".
You could of course write client-side code to call into your Web API and perform the templating/UI client-side with the mass amount of plugins available.
I'm pretty sure the Web API isn't capable of returning templated HTML in the same way an ASP.NET MVC web application can.
So if you want to "re-use" certain portions of your application (repository, domain, etc), it would probably be best to wrap the calls in a facade/service layer of sorts and make both your Web API and seperate ASP.NET MVC web application call into that to reduce code.
All you should end up with is an ASP.NET MVC web application which calls into your domain and builds templated HTML, and an ASP.NET Web API application which calls into your domain and returns various resources (JSON, XML, etc).
If you have a well structured application then this form of abstraction shouldn't be a problem.
I'd suggest developing your application in such a way that you use a single controller to return the initial application assets (html, javascript, etc) to the browser. Create your API / logic in WebAPI endpoint services and access those services via JavaScript. Essentially creating a single page application. Using MVC 4 our controller can return different Views depending on the device (phone, desktop, tablet), but using the same JavaScript all of your clients will be able to access the service.
Good libraries to look into include KnockoutJS, SammyJS , or BackBoneJS
If you do have a requirement to return HTML using the WebAPI e.g. to allow users to
click around and explore your API using the same URL then you can use routing\an html message handler.
public class HtmlMessageHandler : DelegatingHandler
{
private List<string> contentTypes = new List<string> { "text/html", "application/html", "application/xhtml+xml" };
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method == HttpMethod.Get && request.Headers.Accept.Any(h => contentTypes.Contains(h.ToString())))
{
var response = new HttpResponseMessage(HttpStatusCode.Redirect);
var htmlUri = new Uri(String.Format("{0}/html", request.RequestUri.AbsoluteUri));
response.Headers.Location = htmlUri;
return Task.Factory.StartNew<HttpResponseMessage>(() => response);
}
else
{
return base.SendAsync(request, cancellationToken);
}
}
}
For a full example check out:-
https://github.com/arble/WebApiContrib.MessageHandlers.Html
I've played with this idea before. I exposed an API through MVC3 as JSONResult methods on different controllers. I implemented custom security for the API using controller action filters. Then built a very AJAX heavy HTML front-end which consumed the JSON services. It worked quite well and had great performance, as all data transferred for the web app was through AJAX.
Frederik Normen has a good post on Using Razor together with ASP.NET Web API:
http://weblogs.asp.net/fredriknormen/archive/2012/06/28/using-razor-together-with-asp-net-web-api.aspx
One important constraint of a well designed REST service is utilizing "hypermedia as the engine of application state" (HATEOAS - http://en.wikipedia.org/wiki/HATEOAS).
It seems to me that HTML is an excellent choice to support as one of the media formats. This would allow developers and other users to browse and interact with your service without a specially built client. Which in turn would probably result in the faster development of a client to your service. (When it comes to developing actual HTML clients it would make more sense to use a json or xml.) It would also force a development team into a better designed rest service as you will be forced to structure your representations in such a way that facilitates an end users navigation using a browser.
I think it would be smart for any development team to consider taking a similar approach to Frederik's example and create a media type formatter that generates an HTML UI for a rest service based on reflecting on the return type and using conventions (or something similar - given the reflection I would make sure the html media format was only used for exploration by developers. Maybe you only make it accessible in certain environments.).
I'm pretty sure I'll end up doing something like this (if someone hasn't already or if there is not some other feature in the web api that does this. I'm a little new to Web API). Maybe it'll be my first NuGet package. :) If so I'll post back here when it's done.
Creating Html is a job for an Mvc Controller not for Web Api, so if you need something that is able to return both jSon and Html generated with some view engine the best option is a standard Mvc Controller Action methosd. Content Negotiation, that is the format to return, can be achieved with an Action Fiter. I have an action filter that enable the the controller to receive "hints" from the client on the format to return. The client can ask to return a view with a specific name, or jSon. The hint is sent either in the query string or in an hidden field (in case the request comes from a form submit). The code is below:
public class AcceptViewHintAttribute : ActionFilterAttribute
{
private JsonRequestBehavior jsBehavior;
public AcceptViewHintAttribute(JsonRequestBehavior jsBehavior = JsonRequestBehavior.DenyGet)
{
this.jsBehavior = jsBehavior;
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
string hint = filterContext.RequestContext.HttpContext.Request.Params["ViewHint"];
if (hint == null) hint = filterContext.RequestContext.RouteData.Values["ViewHint"] as string;
if (!string.IsNullOrWhiteSpace(hint) && hint.Length<=100 && new Regex(#"^\w+$").IsMatch(hint) )
{
ViewResultBase res = filterContext.Result as ViewResultBase;
if (res != null)
{
if (hint == "json")
{
JsonResult jr = new JsonResult();
jr.Data = res.ViewData.Model;
jr.JsonRequestBehavior = jsBehavior;
filterContext.Result = jr;
}
else
{
res.ViewName = hint;
}
}
}
base.OnActionExecuted(filterContext);
}
}
Now that it's been a little while through the Beta, MS just released the Release Candidate version of MVC4/VS2012/etc. Speaking to the navigation/help pages (mentioned by some other posters), they've added a new IApiExplorer class. I was able to put together a self-documenting help page that picks up all of my ApiControllers automatically and uses the comments I've already put inline to document them.
My recommendation, architecture-wise, as others have said as well, would be to abstract your application into something like "MVCS" (Model, View, Controller, Services), which you may know as something else. What I did was separate my models into a separate class library, then separated my services into another library. From there, I use dependency injection with Ninject/Ninject MVC3 to hook my implementations up as needed, and simply use the interfaces to grab the data I need. Once I have my data (which is of course represented by my models), I do whatever is needed to adjust it for presentation, and send it back to the client.
Coming from MVC3, I have one project that I ported to MVC4, which uses the "traditional" Razor markup and such, and a new project that will be a single page AJAX application using Backbone + Marionette and some other things sprinkled in. So far, the experience has been really great, it's super easy to use. I found some good tutorials on Backbone + Marionette here, although they can be a bit convoluted, and require a bit of digging through documentation to put it all together, it's easy once you get the hang of it:
Basic intro to Backbone.js: http://arturadib.com/hello-backbonejs/docs/1.html
Use cases for Marionette views (I found this useful when deciding how to create views for my complex models): https://github.com/derickbailey/backbone.marionette/wiki/Use-cases-for-the-different-views

Choose the best Client/Server Validation Framework for MVC

Im trying to choose the best server/client validation framework to use with my MVC application. I would like to know what is the best validation framework to use with MVC to do server/client validation.
My options are:
Castle validator
Microsoft Data Annotations
nHibernate Validator
With the upcoming MVC 2, it looks like MS is leaning towards the System.ComponentModel.DataAnnotations library. It's pretty nice - does a lot of code generation for you.
I've been using xVal with great success.
The best thing is you can fully automate validation:
put DataAnnotations (or special rules) to your business layer POCO classes (if you have them) or entity classes' metadata buddy classes if you use entities up to controller layer
write an ActionFilter that will automatically validate parameters to your controller actions - it's best if all your POCOs (or entities) implement a certain interface that defines Validate() method, filter calls this method and fills ModelState.Errors when validation fails.
Add if (ModelState.IsValid) { ... } in your controller action that needs to work differently when model isn't valid
Put <%= Html.ValidationMessage(...) %> in your views that will display validation errors
Add xVal's client validation to your views if desired
This way you've set up automatic object validation. All your controller actions will do is check Model validity.
Asp.net MVC 2 will have something very similar to xVal already built in the framework so it's up to you which version are you using.

ASP.NET MVC - User Input and Service/Repository - Where to do Validation?

This might be too opinionated a question, but looking for help!
I have been trying to refine my ASP.NET MVC program structure. I just started using it at preview 5 and it is my first foray into business application development -- so everyting is new!
At the controller level, I have a service object responsible for talking to the repository and taking care of all business logic. At the action level, I have an object that holds all view data -- user input and generated output -- that I'll call view object (is there a general term for this?). Unlike most examples I see, this object is not a database object, but an object specific to the view.
So now I want to add user validation. The problem is, I'm not sure where to put it. It makes the most sense to me to do it in the Service layer. The Service layer is responsible for all the business logic and validation is business logic. On the other hand, most validation frameworks that I see are for validating an object, which makes me think the view object should be validation aware. Finally, there are some validation methods that would require a database connection (checking if a user input field has a corresponding database record for example), and the view object has no concept of a database, only the Service.
So some options I see are:
Do validation in the Service.Method on the parameters passed to the method.
Do validation in the view object before calling Service.Method.
Do validation in the view object but make the Service.Method require a view object reference so it is initiating the validation on the object.
I'm sure there are more. I'm curious of how other people handle user input validation in the MVC sense. I've previously used the Enterprise Validation Block and liked being able to use stock validators for everything, but I'm not sure how to make it fit into a seperate view object and service layer. It would be easy if they (view object / service) were the same object, which is maybe what people do? Like I said, its all new to me and I'm looking for best practice / patterns.
I typically do basic validation (required fields, email format, etc.) in the controller action when the form is submitted. I then let the business layer handle validation that requires business knowledge. I usually double check the basic stuff in the business layer as well, so if I expose that logic through web services or use it in another application later, I still have validation where it is most important (IMO).
There are some interesting links on this
MVC & MS Validation Application Block
MVC & Data Annotation Validators
Form Validation video
Personally, i've added validation to my Service layer objects (first two links). This way, if any method in any controller decides to call my service method .. the logic is all checked and boxed in one location. DRY.
That said, i also have some UI validation (3rd link) .. to reduce the roundtrip time.
Lastly, the current MVC dll's have the ability to pass error messages back to the UI .. so the view can display them nicely. Check out :-
ViewData.ModelState.AddModelError(key, message)
hth!
Check the following blog posts
http://blog.codeville.net/2008/09/08/thoughts-on-validation-in-aspnet-mvc-applications/
http://www.emadibrahim.com/2008/09/08/client-server-side-validation-in-aspnet-mvc/
Take a look at the S#arp Architecture project. Validation is handled on the model to ensure that no entity is persisted to the database in an invalid state. It does this by using NHibernate.Validator and attaching it to NHibernate's save and update events.
Personally, this approach makes the most sense to me since you don't have to duplicate your validation logic in multiple controllers.
I was afraid I'd get no replies for my post, happy to be wrong!
I've read those links before, but probably a month or more ago, and re-reading them with what I understand now has been very helpful. I really like Steve Sanderson's post with the sliding scale, but wish he would show an example of validating something at the right-end of the spectrum.
As an example in his blog he gives: " 'usernames must be unique' will probably be enforced in your database". So would this be something like:
public static void SavePerson(Person person)
{
// make sure it meets some format requirement
// in this case the object is responsible for validation and the service layer is the caller
person.EnsureValid();
// todo: action to verify username is unique by checking database
// in this case the service layer is responsible for calling and implementing validation
// todo: action to save to database
}
This makes sense, and would show my trouble grasping where to put validation as it is inside both the service layer (very unique name) and view-object (verify formats).
Another concern I have is the service layer starts to balloon with validation logic. Maybe split it out to a different class or something? In my case some validation logic might be shared between services, so I would like to think of a DRY way to implement this. Fun stuff to think about!
Emad Ibrahim's link is great in that once I start to understand this process a bit more I was going to look for a way to generate javascript client-side validation using the same set of rules without having to repeat code. He already has that :)
I have heard about S#arp but not sat down and seen how it works (I'm not sure if there is much in the way of demos on it, or if downloading the code is the demo!). I'm not sure if doing validation on the database model only would be sufficient. It seems to me there would be plenty of valid model states with regards to the database that business logic would say are invalid (such as date ranges / must be before / after / etc). Those are the cases that are wracking my brain :)
Also, a link I liked (googled it after I saw Emad reply to Steves post with BLL and no idea what it meant... duh):
http://en.wikipedia.org/wiki/Business_logic_layer
So I didn't know it, but I think this is the model I'm writing to: Business Process object that handles data interactions, and Business Entities that are logical models rather than database models. I think I need to start reading some more fundamental patterns and practices with this stuff to better understand the concepts (it seems like a lot of this is stuff Java people write vs. .NET people). It might be time to take a step back :)
I have come across this same issue in a recent project. First, to restate the problem, I am trying to follow the domain-centric approach of DDD. I have entities composed into aggregates that can validate themselves, and the repositories verify validity on save. The UI can also get validity information from an aggregate in order to display error feedback to the client. The general approach is to leverage as much as possible ASP.NET MVC's model binding, and validation/form UI helpers. This creates the simple UI flow: 1) bind, 2) validate, 3) if valid, save, else re-populate view.
However, it is not directly obvious how to do leverage ASP.NET MVC and this simple flow when DDD services are involved. Originally, I developed my services as such:
public class SomeProcessService
{
public Result Execute(int anAggregateID, int anotherAggregateID, string someData)
{
// validate input
// if invalid, return failures
// else
// modify aggregates
// using (transaction)
// {
// save aggregates
// commit
// }
// return success
}
}
The problem is that the validation and the save are inextricably linked in the method. To leverage the MVC model binding, we need something that serves as a model to bind to. I am refactoring to this:
public class SomeProcessService
{
public class Request : IValidateable
{
public int AggregateID {get;set;}
public int AnotherAggregateID {get;set;}
public string SomeData {get;set;}
public Result Validate()
{
// validation
}
}
public void Execute(Request request)
{
// validate input by calling request.Validate()
// if invalid, throw new ValidationException(request)
// else
// modify aggregates
// using (transaction)
// {
// save aggregates
// commit
// }
// return success
}
}
This repurposes the Parameter Object pattern to separate method input validation. I can bind to a SomeProcessService.Request object in my controller, as well as get validation information there. If all is well, from my controller I initiate the service call using the Request object as the parameter. This approach seems to happily marry DDD services with ASP.NET MVC validation requirements.

Resources