繁体   English   中英

限制按钮可以被按下的次数-C#ASP.NET MVC5 JavaScript

[英]Limit the number of times a button can be pressed - C# ASP.NET MVC5 JavaScript

我有一个页面允许您创建收入类型,但是如果您连续单击创建按钮,那么它将创建多个条目,是否有办法将其限制为您只按一次就可以了?

我看过使用ajax方法获取信息然后将表单发布到数据库的代码。 我的一些代码如下:

指数

@section scripts {
<script language="javascript" type="text/javascript">
    @* DOM ready? *@
    $(function () {
        @* Pagination Async Partial Handling *@
        $(document).on("click", "#indexPager a", function () {
            if ($(this).parent().hasClass('disabled') || $(this).parent().hasClass('active'))
                return false;
            $.ajax({
                url: $(this).attr("href"),
                type: 'GET',
                cache: false,
                success: function (result) {
                    $('#tableContainer').html(result);
                    addBootstrapTooltips("#tableContainer");
                }
            });
            return false;
        });
        $(document).on("change", "#pageSizeSelector", function () {
            var selectedValue = $(this).val();
            $.ajax({
                url: selectedValue,
                type: 'GET',
                cache: false,
                success: function(result) {
                    $('#tableContainer').html(result);
                    addBootstrapTooltips("#tableContainer");
                }
            });
        });

        @* Sorting Async Partial Handling *@
        $(document).on("click", "#tableHeader a", function () {
            $.ajax({
                url: $(this).attr("href"),
                type: 'GET',
                cache: false,
                success: function (result) {
                    $('#tableContainer').html(result);
                    addBootstrapTooltips("#tableContainer");
                }
            });

            return false;
        });

        @* Apply ACTION colours for hover *@
        addTableStylingScripts();
    });
</script>
}

@section additionalStyles {
    @Styles.Render("~/plugins/datatables/media/css/cssDatatables")
}

@section modal {

}

<article class="row">
    <h1 class="pageTitle artistHeader fw200 mb20 mt10">@ViewBag.Title</h1>

    <div class="col-md-12">
        <div class="panel panel-visible" id="tableContainer">
            @Html.Partial("_IncomeTypeManagementList", Model)
        </div>
    </div>
</article>

IncomeTypeManagementList

@* Header *@
<div class="panel-heading createContentTitle">
    <div class="panel-title createLink">
        <a href="@Url.Action("Create", "IncomeTypeManagement", new
            {
                page = Model.PagingInfo.Page,
                take = Model.PagingInfo.Take,
                sortBy = Model.PagingInfo.SortPropertyName,
                sortAsc = Model.PagingInfo.SortAscending
            })" data-container="body" data-toggle="tooltip" title="Add Income Type" id="createIncomeTypeLink">
            <span class="fa fa-file"></span>&nbsp; Add Income Type
        </a>
    </div>
</div>

@* Body *@
<div class="panel-body pn">
    <table class="table table-striped table-hover dataTable incomeTypesTable admin-form theme-primary" cellspacing="0" width="100%" role="grid">
        <thead id="tableHeader">
            <tr>
                <th class="hidden-xs sorting @Html.SortTitleItem("IncomeTypeGroupId", Model.PagingInfo.SortPropertyName, Model.PagingInfo.SortAscending)">
                    <a href="@Url.Action("Index", "IncomeTypeManagement", new
                             {
                                 page = 1,
                                 take = Model.PagingInfo.Take,
                                 sortBy = "IncomeTypeGroupId",
                                 sortAsc = Model.PagingInfo.SortPropertyName != "IncomeTypeGroupId" || !Model.PagingInfo.SortAscending
                             })" data-container="body" data-toggle="tooltip" title="Sort by group">Group</a>
                </th>
                <th class="sorting @Html.SortTitleItem("Name", Model.PagingInfo.SortPropertyName, Model.PagingInfo.SortAscending)">
                    <a href="@Url.Action("Index", "IncomeTypeManagement", new
                             {
                                 page = 1,
                                 take = Model.PagingInfo.Take,
                                 sortBy = "Name",
                                 sortAsc = Model.PagingInfo.SortPropertyName != "Name" || !Model.PagingInfo.SortAscending
                             })" data-container="body" data-toggle="tooltip" title="Sort by name">Name</a>
                </th>
                <th class="hidden-xs sorting hidden-xs @Html.SortTitleItem("CreatedDate", Model.PagingInfo.SortPropertyName, Model.PagingInfo.SortAscending)">
                    <a href="@Url.Action("Index", "IncomeTypeManagement", new
                             {
                                 page = 1,
                                 take = Model.PagingInfo.Take,
                                 sortBy = "CreatedDate",
                                 sortAsc = Model.PagingInfo.SortPropertyName != "CreatedDate" || !Model.PagingInfo.SortAscending
                             })" data-container="body" data-toggle="tooltip" title="Sort by date">Created</a>
                </th>
                <th class="bg-white">
                    <div class="text-center">Action</div>
                </th>
            </tr>
        </thead>
        <tbody>
            @foreach (var it in Model.IncomeTypes)
            {
                var actionId = "action_" + tableRowIndex;
                var editIncomeTypeId = "editIncomeType_" + tableRowIndex;

                <tr data-id="@it.ID"
                    data-isdeleted="@it.IsDeleted"
                    data-rowversion="@it.RowVersion"
                    data-createddate="@it.CreatedDate"
                    data-name="@it.Name"
                    data-incometypegroupid="@it.IncomeTypeGroupId"
                    data-incometypegroupname="@it.IncomeGroupName">
                    <td class="hidden-xs">
                        @it.IncomeGroupName
                    </td>
                    <td>
                        @it.Name.Truncate(50)
                    </td>
                    <td class="hidden-xs">
                        @it.CreatedDate.ToShortDateString()
                    </td>
                    <td class="updateTableRow text-center">
                        <div class="dropdownContainer btn-group text-right">
                            <button type="button" class="btn btn-primary br2 btn-xs fs12 dropdown-toggle" data-toggle="dropdown" aria-expanded="false" id="@actionId">
                                Action
                                <span class="caret ml5"></span>
                            </button>
                            <ul class="dropdown-menu dropdown-menu-right" role="menu">
                                <li>
                                    <a href="@Url.Action("Update", "IncomeTypeManagement", new
                                        {
                                            id = it.ID,
                                            page = Model.PagingInfo.Page,
                                            take = Model.PagingInfo.Take,
                                            sortBy = Model.PagingInfo.SortPropertyName,
                                            sortAsc = Model.PagingInfo.SortAscending
                                        })" data-container="body" data-toggle="tooltip" id="@editIncomeTypeId" title="Edit" data-rowhover="editTableRow">
                                        Edit
                                    </a>
                                </li>
                            </ul>
                        </div>
                    </td>
                </tr>
                tableRowIndex++;
            }
        </tbody>
    </table>
    @Html.Partial("_Pagination", Model.PagingInfo)
</div>

创造

@section scripts {
    @Scripts.Render("~/bundles/jqueryajaxval")
    @Scripts.Render("~/bundles/jqueryval")

    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            @* Cancel *@
            $(document).on("click", "#CancelForm", function (e) {
                var uri = '@Html.Raw(Url.Action("Index", "IncomeTypeManagement", new 
                { 
                    page = Model.PagingInfo.Page, 
                    take = Model.PagingInfo.Take,
                    sortBy = Model.PagingInfo.SortPropertyName,
                    sortAsc = Model.PagingInfo.SortAscending
                }))';

                window.location = uri;
                    e.preventDefault();
            });
        });
    </script>
}

@section additionalStyles {

}

@section modal {

}

<article class="row">
    <h1 class="pageTitle incomeTypeHeader fw200 mb20 mt10">@ViewBag.Title</h1>

    <div class="col-md-1"></div>
    <div id="incomeTypeResults" class="col-md-10 formContainer">
        <div class="panel">
            <div class="panel-heading">
                <span class="panel-title">
                    <i class="glyphicon glyphicon-pencil"></i>&nbsp;Details Of New Income Type
                </span>
            </div>

            @using (Html.BeginForm("Create",
                                   "IncomeTypeManagement", FormMethod.Post,
                                   new { id = "createIncomeType", role = "form", @class = "theme-primary form-horizontal" }))
            {
                @Html.AntiForgeryToken()

                @* Pagination / Sorting *@
                @Html.HiddenFor(m => m.PagingInfo.Page)
                @Html.HiddenFor(m => m.PagingInfo.Take)
                @Html.HiddenFor(m => m.PagingInfo.SortPropertyName)
                @Html.HiddenFor(m => m.PagingInfo.SortAscending)

                <fieldset>
                    <legend style="display: none">Create Income Type Form</legend>
                    @Html.HiddenFor(m => m.IsDeleted)

                    <div class="panel-body p25 fill bt0">
                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                        <div class="form-group">
                            @Html.LabelFor(m => m.IncomeTypeGroupId, new { @class = "control-label col-lg-2" })
                            <div class="col-lg-8">
                                @{
                                    // get drop down values for DropDownFor()
                                    var selectableItems = incomeTypeGroups.Select((v, idx) => new SelectListItem
                                    {
                                        Text = v.Value,
                                        Value = v.Key,
                                        Selected = idx == 0
                                    });
                                }
                                @Html.DropDownListFor(m => m.IncomeTypeGroupId, selectableItems, new { @class = "form-control" })
                                @Html.ValidationMessageFor(m => m.IncomeTypeGroupId, string.Empty, new { @class = "text-danger" })
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.LabelFor(m => m.Name, new { @class = "control-label col-lg-2" })
                            <div class="col-lg-8">
                                @Html.TextBoxFor(m => m.Name, new { @class = "form-control", id = "Name", placeholder = "Name..." })
                                @Html.ValidationMessageFor(m => m.Name, string.Empty, new { @class = "text-danger" })
                            </div>
                        </div>
                    </div>

                    <div class="panel-footer">
                        <div class="text-center">
                            <input type="button" class="btn btn-primary" id="CancelForm" value="Cancel" />
                            <input type="submit" class="btn btn-primary" id="SubmitForm" value="Create" />
                        </div>
                    </div>

                </fieldset>
            }
        </div>
    </div>
</article>

更新资料

section scripts {
    @Scripts.Render("~/bundles/jqueryajaxval")
    @Scripts.Render("~/bundles/jqueryval")

    <script language="javascript" type="text/javascript">
        $(document).ready(function () {
            @* Cancel *@
            $(document).on("click", "#CancelForm", function (e) {
                var uri = '@Html.Raw(Url.Action("Index", "IncomeTypeManagement", new
                {
                    page = Model.PagingInfo.Page,
                    take = Model.PagingInfo.Take,
                    sortBy = Model.PagingInfo.SortPropertyName,
                    sortAsc = Model.PagingInfo.SortAscending
                }))';

                window.location = uri;
                e.preventDefault();
            });
        });
    </script>
}

@section additionalStyles {

}

@section modal {

}

<article class="row">
    <h1 class="pageTitle incomeTypeHeader fw200 mb20 mt10">@ViewBag.Title</h1>

    <div class="col-md-1"></div>
    <div id="incomeTypeResults" class="col-md-10 formContainer">
        <div class="panel">
            <div class="panel-heading">
                <span class="panel-title">
                    <i class="glyphicon glyphicon-pencil"></i>&nbsp;Details Of '@Model.Name'
                </span>
            </div>

            @using (Html.BeginForm("Update",
                                   "IncomeTypeManagement", FormMethod.Post,
                                   new { id = "updateIncomeType", role = "form", @class = "theme-primary form-horizontal" }))
            {
                @Html.AntiForgeryToken()

                @* Pagination / Sorting *@
                @Html.HiddenFor(m => m.PagingInfo.Page)
                @Html.HiddenFor(m => m.PagingInfo.Take)
                @Html.HiddenFor(m => m.PagingInfo.SortPropertyName)
                @Html.HiddenFor(m => m.PagingInfo.SortAscending)


                <fieldset>
                    <legend style="display: none">Edit Income Type Form</legend>
                    @Html.HiddenFor(m => m.ID)
                    @Html.HiddenFor(m => m.RowVersion)
                    @Html.HiddenFor(m => m.IsDeleted)

                    <div class="panel-body p25 fill bt0">
                        @Html.ValidationSummary(true, "", new { @class = "text-danger" })
                        <div class="form-group">
                            @Html.LabelFor(m => m.IncomeTypeGroupId, new { @class = "control-label col-lg-2" })
                            <div class="col-lg-8">
                                @{
                                    // get drop down values for DropDownFor()
                                    var selectableItems = incomeTypeGroups.Select((v, idx) => new SelectListItem
                                    {
                                        Text = v.Value,
                                        Value = v.Key,
                                        Selected = Model.IncomeTypeGroupId.ToString() == v.Key
                                    });
                                }
                                @Html.DropDownListFor(m => m.IncomeTypeGroupId, selectableItems, new { @class = "form-control" })
                                @Html.ValidationMessageFor(m => m.IncomeTypeGroupId, string.Empty, new { @class = "text-danger" })
                            </div>
                        </div>

                        <div class="form-group">
                            @Html.LabelFor(m => m.Name, new { @class = "control-label col-lg-2" })
                            <div class="col-lg-8">
                                @Html.TextBoxFor(m => m.Name, new { @class = "form-control", id = "Name", placeholder = "Name..." })
                                @Html.ValidationMessageFor(m => m.Name, string.Empty, new { @class = "text-danger" })
                            </div>
                        </div>
                    </div>

                    <div class="panel-footer">
                        <div class="text-center">
                            <input type="button" class="btn btn-primary" onclick="this.disabled = true" id="CancelForm" value="Cancel" />
                            <input type="submit" class="btn btn-primary" id="SubmitForm" value="Update" />
                        </div>
                    </div>

                </fieldset>
            }
        </div>
    </div>
</article>

因此,我尝试添加<input type="submit" class="btn btn-primary" id="SubmitForm" value="Update" onclick="this.disabled = true" />

在“ 创建”页面上单击“添加收入Tye”后,您将被转到“创建”页面,但是当我进行捆绑测试时,该按钮被禁用,但是它没有提交任何内容,仅保留在“ 创建”页面上

要回答您的问题,您必须从两个角度解决问题:

  1. 单击按钮后,您可以将其禁用或显示一个叠加层,以便页面上的其他任何元素都无法与之交互
  2. 您还必须考虑如果某些恶意用户多次重放请求(通过绕过或更改UI,这很容易做到)会发生什么情况,那么在服务器端,您可以使用请求的处理队列,并且每次需要要添加新的处理请求,您可以检查是否存在重复项

不幸的是,这没有一个简单的答案。 答案的第二部分必须考虑它,并评估您是否遇到此问题。 如果您的应用程序是公开的,并且任何人都可以访问它,请不要假设用户仅通过UI就能完成系统上的所有操作。

希望这可以帮助。

这是我想出的:

<script language="javascript" type="text/javascript">
        $('.form-disable').on('submit', function () {
            var self = $(this),
                button = self.find('input[type="submit"], button'),
                submitValue = button.data('submit-value');
            button.attr('disabled', 'disabled').val((submitValue) ? submitValue : 'Please Wait...');
        });
</script>

我在表单中添加了一个类,以便当您单击用于处理提交的按钮时,它将禁用该按钮,然后等待消息。 但是它只允许单击一次按钮。

暂无
暂无

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

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