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

时间:2018-04-20 10:01:34

标签: javascript c# jquery ajax asp.net-mvc-5

我有一个允许您创建收入类型的页面,但是如果您单击“创建”按钮,则会连续创建多个条目,是否有办法将其限制为您按一下这就是它?

我查看了它使用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时,您将被定向到创建页面,但是当我绑定测试时,该按钮被禁用,但它不会提交任何内容而只是保留在创建页面

2 个答案:

答案 0 :(得分:0)

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

  1. 点击按钮后,您可以将其停用或显示叠加层,以便页面上的其他元素无法与之互动
  2. 你还必须考虑如果一些恶意用户多次重放该请求会发生什么(通过绕过或改变UI - 这很容易做到) - 在服务器端你可以使用处理队列的请求和每一个如果您想添加新的处理请求,可以查看是否存在重复
  3. 不幸的是,没有一个简单的答案。答案的第二部分你必须考虑并评估你是否接触过这个问题。如果您的应用程序是公开的,并且任何人都可以访问它,请不要假设用户只通过UI在您的系统上执行所有操作。

    希望这有帮助。

答案 1 :(得分:0)

这就是我想出的:

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

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