How to hook into error of jQuery validate unobtrusive in MVC 3?
Asked Answered
P

2

15

Looking for a way to hook into the client side fail condition for the form.

I need to re-enable a submit button if the validation fails so they can try again.

I found the following: Using unobtrusive validation in ASP.NET MVC 3, how can I take action when a form is invalid? which might work but I was hoping to do this from a central place as the form can be submitted from several places.

Update:

This function seems to work well assuming you have an input tag with the class ".goButton".

<script language="javascript" type="text/javascript">
    $(".goButton").click(function () {
        if (!$(this).closest("form").valid()) {
            return false;
        }
        $(".goButton").after("Please wait...");
        $(".goButton").hide();
    });
</script>
Psychopathology answered 27/6, 2011 at 13:58 Comment(0)
B
26

Then you can hook ALL forms from a central place - just be aware all forms will be hooked. Instead of using $("#formId") in the sample, simply use $("form").submit() and that delegate will be called for any form's submit and in that method you can call your validate check and return true (to submit the form) or false to prevent it.

Something like this off the top of my head

$("form").submit(function () {
  if (!$(this).valid()) {
      return false;
  }
  else
  {
      return true;
  }
});
Barbosa answered 27/6, 2011 at 19:43 Comment(2)
Thank you, I believe that is what I was looking for.Psychopathology
Calling $(this).valid() here actually runs the validation logic which was exactly what i was looking for. I was having trouble gaining a count of .form-validation-error elements within a $(form).submit() event until calling $(this).valid(). Thx much!Caty
D
0

I have away to achieve the OPs question, its simpler and more customisable:

In the C# MVC Controller:

[HttpPost]
public ActionResult CreateDirectory(string DirectoryName)
{
    return Content("Success");
}

In Page JQuery:

<script>
var jqxhr = $.post("/<Directory>/<File>", { myString: longString }, function () {
    if(jqxhr.responseText == 'Success')
        alert('Yay its working!');
    else
        alert('Failure its not working!');
})
.done(function () {
    //alert("second success");
})
.always(function () {
    //alert("finished");
})
.fail(function () {
    alert("Connection Error! Either the Server is offline or there is no internet connection.");
});
<script>

Of course, this is fully customisable and works a treat! By editing the Controller and JQuery code to suit your proposes.

This like handles the JQuery side:

if(jqxhr.responseText == 'Success') alert('Yay its working!');
Dagostino answered 1/12, 2020 at 7:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.