问题
I am creating an ASP.NET MVC 5 application. There is a long wait time between the user clicking the "submit" button and the next page to load, so I would like a "please wait" modal to pop up only if the user has submitted a valid form.
I have tried the following code, which causes the modal to pop up no matter if the form is valid or not:
$('form').submit(function () {
$('#waitingModal').show();
});
My application utilizes the jQuery Validate plugin and unobtrusive validation which both came with creating a MVC application, so I tried this code:
$('form').submit(function () {
if ($(this).valid()) {
$('#waitingModal').show();
}
});
But I am getting the following error:
TypeError: $(...).valid is not a function
The NuGet Manager says that I am working with jQuery version 1.11.1, jQuery Validate 1.11.1, and jQuery Unobtrusive 3.2.3.
Am I missing something in my code? Is there another approach?
回答1:
Thanks to your comments and this post, I was able to solve my problem. Posting a solution here for anyone else who runs into this issue...
I added .validate() to my code like so:
$('form').submit(function () {
$(this).validate();
if ($(this).valid()) {
$('#waitingModal').show();
}
});
But ran into to the same error:
TypeError: $(...).validate is not a function
After Googling and finding this post, I thought I'd try rearranging my script tags. Even though my jQuery script tag resides in my Layout.cshtml, I needed to move my script tag to jQuery Validate on the form's view to the bottom of the script tag list. Now the modal is popping up exactly how I would like it to.
EDIT
Per another user's comment, I removed .validate(); from my code. So my code is back to this:
$('form').submit(function () {
if ($(this).valid()) {
$('#waitingModal').show();
}
});
Just as the user said, the code ran perfectly fine without the .validate(); Turns out my only issue was the order of my script tags.
回答2:
You need to use the Ajax Callback function of JQuery. It maybe a Http Post or Get Call. For your "submit" scenario, It's should be a POST call.
For example:
var element = $('#dialogContent');
element.html('please wait...');
element.dialog("open");
$.ajax(url, {
data: { "_": $.now() },
contentType: 'text/html',
dataType: 'html',
type: 'POST'
}).done(function (data) {
setTimeout(function () {
element.html(data);
}, 100);
return false;
}).fail(function (error) {
element.html('Show error information here..');
}
);
来源:https://stackoverflow.com/questions/46715241/trigger-modal-if-submitting-valid-form-in-asp-net-mvc-5-application