marți, 17 septembrie 2013

Ajax Form Validation in ASP.NET MVC

One thing that I like when using regular forms in ASP.NET MVC is the good integration with jQuery Validation. Is practical, easy to use and addresses both property and model validation.

HouseController.cs: HouseEdit.cshtml Unfortunately, it doesn't provide the same experience using Ajax Forms. Somehow, I wanted to use the same approach when validating a form submit using Ajax. In a simple submit action, I wanted to look like similar to this:

HouseController.cs
Starting from what I needed to do, I began constructing the missing pieces. First, the ToAjaxValidationErrors which gave me some trouble, at first:

This was basically all I could do on the server side. I had to start working on the client side to provide some handling logic on what the CreateHouse action would return. First I had to intercept the Form's Submit action:

This looked promising. Of course, nothing works just yet, but I managed to get where I wanted: using the jQuery Validation itself to change reproduce the behavior of regular forms. Now I needed to provide the actual implementation of showAjaxErrors method and in its most basic form, it wasn't more complicated than this:

And that's it, should be enough to get one started.

Good Luck!