Intercept data validation failures on submitting a form
I'm writing a form in ASP.NET MVC 3 (but things can be similar in other environments). On submitting a form, I want to disable the page, because server processing is a bit long, so I want to avoid the user clicking twice on the buttons. I use the blockUI plugin function, like in:
<script type="text/javascript">
jQuery(document).ready(function () {
$('#AddUserForm').submit(function () {
$.blockUI();
});
});
</script>
I do not worry about UN-blocking the UI, because my form submitting generates a new page loading, so things start from the beginning anyway. The problem is that my form uses data validation attributes, as in
<input class="text-box single-line" data-val="true" data-val-required="The UserName field is required." id="UserName" name="UserName" type="text" value="" />
so if a field is not validated correctly, the form IS submitted (my code is executed, blocking the UI), but the page is not even reloaded, so I'm totally blocked.
Does anyone know if there's an eve开发者_如何学Cnt to intercept, for this case, or a useful alternative? Thanks in advance. Andrea Bioli
With mvc3, ClientValidationEnabled and UnobtrusiveJavaScriptEnabled in web.config you could simply use in your submit:
if ($("form:first").valid()) { $.blockUI({ message: 'Un instant svp...' }); }
Look at the preventDefault method.
<script type="text/javascript">
jQuery(document).ready(function () {
$('#AddUserForm').submit(function (event) {
event.preventDefault();
$.blockUI();
});
});
</script>
精彩评论