Frage

I'm trying to put a jQuery animated loader on my asp.net mvc 4 application where when a user clicks on the submit button it will overtake the whole screen with a white wash and a please wait. This all works. The part I'm having a problem with is that when there is a validation error on my form, the client side validation kicks in (which I want to preserve) and it trapped behind the jquery loader screen. I'm calling the loader like so:

        $(function () {
            $("#submitbtn").click(function () {
                $("#loading").fadeIn();
            });
        });

in my $(document).ready(.... function. My first thought was to use

        @if (ViewData.ModelState.IsValid)
        {
            <text>$(function () {
                $("#submitbtn").click(function () {
                    $("#loading").fadeIn();
                });
            });</text>
        }

but when the page loads this is valid and it will write it out (my bad I should have known). Now I'm at a loss, I'm not sure how to do this. Can anyone help?

War es hilfreich?

Lösung

I'll take a shot at it based on how I understood your problem. So you have:

    $(function () {
        $("#submitbtn").click(function () {
            $("#loading").fadeIn();
            if (validFormInputs()) {                   
                yourForm.submit();
            }
            else {
                // hide the laoder again
                $("#loading").fadeOut(); // or .hide or however you want to hide it
            }
        });
    });

Now the loader may not show at all if the submit action happens too quickly, since the submit is a post back and not an ajax post. If on the server-side there is an error that was not caught by your client-side validation then you can just return the view again and you do not have to do something special on your javascript. So your method may look like this:

[HttpPost]
public ActionResult Edit(YourModel input) {
    if (!ModelState.IsValid) {
        return View(input);
    }

    // do something here, redirect or return the view again
}

Again, please take note that this code is for a post back action and NOT for an ajax post.

UPDATE: So basically here is the step:

  1. Capture the click event of your submit button $("#submitbtn").click(function ()...
  2. Show your loader $("#loading").fadeIn();
  3. Do the client side validation validFormInputs()
  4. If validation fails then hide your loader $("#loading").fadeOut();

    4a. Assumes you are using a validation plugin or in any case, you should have shown the error messages

  5. If the validation succeeds then you submit the form yourForm.submit();

  6. If server-side validation fails then you return the view return View(input);

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top