form data cancel before after jquery asp.net-mvc-3 validation preventdefault

data - jquery submit form on button click



Detener formulario de enviar, utilizar Jquery (5)

Estoy intentando evitar que mi formulario se envíe si falla una validación. Intenté seguir esta publicación anterior pero no funcionó para mí. ¿Qué me estoy perdiendo?

<input id="saveButton" type="submit" value="Save" /> <input id="cancelButton" type="button" value="Cancel" /> <script src="../../Scripts/jquery-1.4.1-vsdoc.js" type="text/javascript"></script> <script type="text/javascript"> $(document).ready(function () { $("form").submit(function (e) { $.ajax({ url: ''@Url.Action("HasJobInProgress", "ClientChoices")/'', data: { id: ''@Model.ClientId'' }, success: function (data) { showMsg(data, e); }, cache: false }); }); }); $("#cancelButton").click(function () { window.location = ''@Url.Action("list", "default", new { clientId = Model.ClientId })''; }); $("[type=text]").focus(function () { $(this).select(); }); function showMsg(hasCurrentJob, sender) { if (hasCurrentJob == "True") { alert("The current clients has a job in progress. No changes can be saved until current job completes"); if (sender != null) { sender.preventDefault(); } return false; } } </script>


De nuevo, AJAX es asincrónico. Entonces se llamará a la función showMsg solo después de la respuesta exitosa del servidor ... y el evento de envío de formularios no esperará hasta el éxito de AJAX.

Mueva el e.preventDefault(); como primera línea en el controlador de clics.

$("form").submit(function (e) { e.preventDefault(); // this will prevent from submitting the form. ...

Vea el código a continuación,

Quiero que se permita HasJobInProgress == False

$(document).ready(function () { $("form").submit(function (e) { e.preventDefault(); //prevent default form submit $.ajax({ url: ''@Url.Action("HasJobInProgress", "ClientChoices")/'', data: { id: ''@Model.ClientId'' }, success: function (data) { showMsg(data); }, cache: false }); }); }); $("#cancelButton").click(function () { window.location = ''@Url.Action("list", "default", new { clientId = Model.ClientId })''; }); $("[type=text]").focus(function () { $(this).select(); }); function showMsg(hasCurrentJob) { if (hasCurrentJob == "True") { alert("The current clients has a job in progress. No changes can be saved until current job completes"); return false; } else { $("form").unbind(''submit'').submit(); } }


Este es un código de JQuery para evitar enviar

$(''form'').submit(function (e) { if (radioButtonValue !== "0") { e.preventDefault(); } });


Pruebe el código a continuación. e.preventDefault () fue agregado . Esto elimina la acción de evento predeterminada para el formulario.

$(document).ready(function () { $("form").submit(function (e) { $.ajax({ url: ''@Url.Action("HasJobInProgress", "ClientChoices")/'', data: { id: ''@Model.ClientId'' }, success: function (data) { showMsg(data, e); }, cache: false }); e.preventDefault(); }); });

Además, ¿mencionó que quería que el formulario no se envíe bajo la premisa de la validación, pero no veo la validación del código aquí?

Aquí hay un ejemplo de alguna validación adicional

$(document).ready(function () { $("form").submit(function (e) { /* put your form field(s) you want to validate here, this checks if your input field of choice is blank */ if(!$(''#inputID'').val()){ e.preventDefault(); // This will prevent the form submission } else{ // In the event all validations pass. THEN process AJAX request. $.ajax({ url: ''@Url.Action("HasJobInProgress", "ClientChoices")/'', data: { id: ''@Model.ClientId'' }, success: function (data) { showMsg(data, e); }, cache: false }); } }); });


Un enfoque diferente podría ser

<script type="text/javascript"> function CheckData() { //you may want to check something here and based on that wanna return true and false from the function. if(MyStuffIsokay) return true;//will cause form to postback to server. else return false;//will cause form Not to postback to server } </script> @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" })) { ......... ......... ......... ......... <input type="submit" value= "Save Employee" onclick="return CheckData();"/> }


usa esto también:

if(e.preventDefault) e.preventDefault(); else e.returnValue = false;

Becoz e.preventDefault () no es compatible con IE (algunas versiones). En IE es e.returnValue = false