free hit counter
November, 2011 - Pietro Brambati Blog - Site Home - MSDN Blogs

Pietro Brambati Blog

Developer's stories

November, 2011

  • Pietro Brambati Blog

    Lazy Remote Validation with ASP.NET MVC 3

    • 0 Comments

    …Or How to prevent unnecessary http call on Remote Validation with ASP.NET MVC 3 and JQuery.

    One of the cooler features with ASP.NET MVC 3 is Remote Validation. In a nutshell you can create a method on a controller class, putting the attribute Remote on your model and having jQuery.Validator plugin making an HTTP call to the controller to perform a custom validation logic that requires server-side logic, like for example check if a product name already exists on your database.

    The JQuery.Validator plugin, in documentation says that: “Once a field was marked invalid, it is eagerly validated: As soon as the user entered the necessary value, the error message is removed”. This works great for me in case I have a field and the validation happens only client-side, but in case of a remote validation scenario, what happens is that an HTTP call is made every time user press a key.

    If you look to what happens with a developer toolbar, you will see that every time you type a char an HTTP call is done. In the following image you see 4 HTTP calls. After the first one I press the tab key, a call is made and the field is marked as invalid, so I go back to the “ProductName” text box, and after that every time a press a key the JQuery.Validator eagerly try to validate remotely and make an HTTP call.

    clip_image002

    I want to avoid these calls every time and also I don’t want to to modify the two out of the box jquery file used by ASP.NET MVC: jquery.validate.js and jquery.validate.unobtrusive.js. My solution is to use the onkeyup event of the jQuery.Validate plugin and search for the html element that use the data-val-remote-url attribute and in that case prevent validation.

    Here the code I have used in the razor view:

    clip_image003

    This helps me to reduce the HTTP calls as outlined in the following image. Here I have only 2 HTTP calls: the first one when I change the focus the first time, so that the HTML field became invalid and the second the second time. Note that I’ve written the same numbers of keys between the first and the second time as before, but now I have less calls.

    clip_image005

    The side effect to this solution is that validation on other fields with other validators start eagerly on every keyup event, but this could be considered reasonable in many situations.

    You can download the javascript file from here.

    I hope this snippet could help others that want to achieve the same result.

Page 1 of 1 (1 items)