提交按钮不调用操作

submit button does not invoke the action

本文关键字:操作 调用 按钮 提交      更新时间:2023-09-26

我使用下面的按钮,它工作正常,并按预期调用操作,

save按钮

 @using (Html.BeginForm("edit", "user", FormMethod.Post, new { enctype = "multipart/form-data" }))
    {
            <div class="form-group">
                <div class="col-md-offset-2 col-md-10">
                    <input type="submit" id="actionbtn" value="Save"  name="buttonType" />
                </div>
            </div>
    }
<<p> 检查按钮/strong>
@using (Html.BeginForm("Check", "User"))
{
    <input type="submit" id="btnConnect" value="Check"  />
    <span id='result'></span>
}

现在,当我添加以下代码时,如果操作成功与否,应该添加一些文本,保存按钮不调用操作,我在这里做错了什么?

$("form").submit(function (e) {
        // Cancel the default submission
        e.preventDefault();
        // Perform the AJAX call
        var target = $(this).attr('action');
        $.post(target, function(result) {
            // Check the value of  result
            if (result === "True") {
                // It was successful, make  result text green.
                $("#result").css('color', 'green').html("successful.");
            } else {
                // Otherwise, it failed, display as red.
                $("#result").css('color', 'red').html("Failed");
            }
        });
    });

我已经尝试删除e.p preventdefault ();没有成功…

你需要像这样检查表单是通过哪个按钮提交的。

你必须这样做来限制它:

$("form").submit(function (e) {
        // Cancel the default submission
        e.preventDefault();
 if($(this).find('input[type="submit"]').val() === "Check") // form submitted via Check button
 {
        // Perform the AJAX call
        var target = $(this).attr('action');
        $.post(target, function(result) {
            // Check the value of  result
            if (result === "True") {
                // It was successful, make  result text green.
                $("#result").css('color', 'green').html("successful.");
            } else {
                // Otherwise, it failed, display as red.
                $("#result").css('color', 'red').html("Failed");
            }
        });
}
else
{
// form submitted from Save button
}
    });

首先你需要添加ID到你的表单:

@using (Html.BeginForm("Check", "User",FormMethod.Post, new { Id = "CheckForm" })

然后你需要添加提交事件处理程序,只需要表单:

$("#CheckForm").submit(function (e) {
    // Cancel the default submission
    e.preventDefault();
    // Perform the AJAX call
    var target = $(this).attr('action');
    $.post(target, function(result) {
        // Check the value of  result
        if (result === "True") {
            // It was successful, make  result text green.
            $("#result").css('color', 'green').html("Successful.");
        } else {
            // Otherwise, it failed, display as red.
            $("#result").css('color', 'red').html("Failed");
        }
    });
});

还有一件事。当Ajax像这样提交时,它会提交一个空表单。是你需要的吗?