繁体   English   中英

ASP.NET MVC核心-阻止多表单提交?

[英]ASP.NET MVC Core - Preventing multiple form submission?

我正在设计一个时钟网络应用程序,在主页上,用户可以在其中有/没有当前活动记录的情况下(从SQL Server数据库中)获取/退出时钟

我有以下表格:

<form asp-action="RegisterClockAction" asp-antiforgery="false" method="post">
    <div class="form-group">
        <input asp-for="ActiveFlag" type="hidden"/>
    </div>
    <div class="form-group row">
        <div class="col-sm-5 offset-sm-1 center-column">
            <button id="clock-in-btn" type="submit" class="btn clock-button" disabled>Clock In</button>
        </div>
        <div class="col-sm-5 center-column">
            <button id="clock-out-btn" type="submit" class="btn clock-button" disabled>Clock Out</button>
        </div>
    </div>
</form>

然后我有以下针对该特定视图的JavaScript

<script type="text/javascript">
    $(function() {
        const activeFlag = @Html.Raw(Json.Serialize(Model.ActiveFlag));
        if (activeFlag) {
            $("#clock-out-btn").prop("disabled", false);
        } else {
            $("#clock-in-btn").prop("disabled", false);
        }
    });

    $("form").submit(function() {
        if ($(this).valid()) {
            $(this).find(":submit").attr("disabled", "disabled");
        }
    });
</script>

现在,表单提交事件确实可以防止重复提交,但这是我应该做的正确方法吗?

不知道是否有必要知道,但是所有的控制器POST操作都知道,如果active标志为true,则我们在数据库中找到记录,对其进行更新并提交更改以将其标记为inactive。 否则,我们将创建一条新记录以追加到数据库中。 然后,我只是重定向回到索引视图以重建模型。

您可以使用javascript来解决此问题

您应该使用event.preventDefault()以便不会再次触发事件的默认操作。

 $("form").submit(function(e) { // 'e' <- add this line of code
     e.preventDefault(); // <- add this line of code
     if ($(this).valid()) {
        $(this).find(":submit").attr("disabled", "disabled");
     }
 });

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM