A Client Validation Issue in MVC 3 and MVC 4(Beta)

 

Introduction:



              Recently while working on an application I ran into an client side validation issue. The issue was that ASP.NET MVC 3 application ignoring the cancel class(which is used to disable the validation of a particular submit button), when you use unobtrusive ajax(for example, Ajax.BeginForm helper). This issue is also present in ASP.NET MVC 4 Beta at two places. Ben Reich raised this issue at http://aspnet.codeplex.com/workitem/7964. In this article, I will show you the issue and a quick solution.

 

Description:

 

             To understand this issue just add s Ajax.BeginForm helper with a submit button in your ASP.NET MVC 3(or ASP.NET MVC 4) application. Set the submit button class to 'cancel'. Run this application. You will find that the application is ignoring 'cancel' class(which is used to disable validation). Similarly, add a submit button with 'cancel' class inside new Login popup of ASP.NET MVC 4 Beta application, you will get the same issue. To resolve this issue just open AjaxLogin.js file(for only ASP.NET MVC 4 Beta) and replace this,

 

        .submit(formSubmitHandler)

 

         with,

 

        .submit(formSubmitHandler)
        .end()
        .find('input[type=submit]')
        .click(function () {
                $(this).closest('form').data('elem', $(this));
        })

  

       and then replace this ,

 

        if (!$form.valid || $form.valid()) {

 

       with,

 

        var $target = $form.data('elem');
        if ($target.hasClass('cancel') || !$form.valid || $form.valid()) {

 

       Then just open jquery.unobtrusive-ajax(.min).js file(both in MVC 3 and MVC 4) and replace this,

 

        
        $(form).data(data_click, name ? [{ name: name, value: evt.target.value}] : []);

 

        with,

 

        $(form).data("elem", $(evt.target));
        $(form).data(data_click, name ? [{ name: name, value: evt.target.value}] : []);

 

        and then replace this,

 

        if (!validate(this)) {

 

        with,

 

        var $form = $(this), $target = $form.data("elem");
        if (!$target.hasClass("cancel") && !validate(this)) {

 

        Now run the application you will find that the issue is resolved.

 

Summary:

 

              In this article, I showed you a client side validation issue in ASP.NET MVC 3 and ASP.NET MVC 4 Beta. I also showed how to quickly resolve this issue. Hopefully you will enjoy this simple article too.

3 Comments

Comments have been disabled for this content.