54

検証が失敗した場合、フォームの送信を停止しようとしています。この前の投稿に従ってみましたが、うまくいきません。私は何が欠けていますか?

<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>
4

5 に答える 5

105

繰り返しますが、AJAX は非同期です。したがって、showMsg 関数は、サーバーからの成功応答の後にのみ呼び出されます。フォーム送信イベントは、AJAX が成功するまで待機しません。

e.preventDefault();クリック ハンドラの最初の行として移動します。

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

以下のコードを参照してください。

許可したい 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();
    }
}
于 2012-04-10T16:26:06.830 に答える
15

これも使用してください:

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

Becoz e.preventDefault()は IE ではサポートされていません (一部のバージョン)。IE ではe.returnValue = falseです

于 2012-11-15T17:18:08.903 に答える
3

以下のコードを試してください。 e.preventDefault() が追加されました。これにより、フォームのデフォルトのイベント アクションが削除されます。

 $(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();
    });
});

また、検証を前提としてフォームを送信しないようにしたいとおっしゃいましたが、コードの検証はありませんか?

追加された検証の例を次に示します

 $(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
       });
     }


    });
 });
于 2012-04-10T16:29:11.823 に答える
3

別のアプローチが考えられます

    <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();"/>
    }
于 2014-08-15T18:07:36.393 に答える