Web Api只允许提交表单一次
问题描述:
我在我的MVC项目中使用web api,并遇到了问题,如果用户在创建页面上......填写表单并提交提交..在处理时间内,用户可以连续点击提交按钮进行多项创作。Web Api只允许提交表单一次
我的目标
只允许用户一次提交表单。基本上,用户点击后,或点击键盘输入或用户提交表格..它应该只允许1次。
我研究了this。
但我该如何实现?这是我到目前为止:
<input id="Edit-Btn-Submit" type="submit" value="Save" class="btn btn-primary" />
$("form").data("validator").settings.submitHandler =
function(form) {
$.ajax({
method: "PUT",
url: infoGetUrl + itemId,
data: $("form").serialize(),
beforeSend: function() {
disableSendButton();
},
complete: function() {
enableSendButton();
},
success: function() {
toastr.options = {
onHidden: function() {
window.location.href = newUrl;
},
timeOut: 3000
}
toastr.success("Equipment successfully edited.");
},
error: function(jqXHR, textStatus, errorThrown) {
var status = capitalizeFirstLetter(textStatus);
var error = $.parseJSON(jqXHR.responseText);
//console.log(error);
var modelState = error.modelState;
//console.log(error.modelState);
$.each(modelState,
function(key, value) {
var id = "";
if (key === "$id") {
id = "#" +
key.replace('$', '').substr(0, 1).toUpperCase() +
key.substr(2);
} else {
id = "#" +
key.replace('$', '').substr(0, 1).toUpperCase() +
key.substr(1);
var status = capitalizeFirstLetter(textStatus);
toastr.error(status + " - " + modelState[key]);
}
var input = $(id);
console.log(id); // result is #id
if (input) { // if element exists
input.addClass('input-validation-error');
}
});
}
});
}
function capitalizeFirstLetter(string) {
return string.charAt(0).toUpperCase() + string.slice(1);
}
function disableSendButton() {
$('#Edit-Btn-Submit').prop('disabled', true);
}
function enableSendButton() {
$('#Edit-Btn-Submit').prop('disabled', false);
}
});
任何帮助表示赞赏。
答
我解决您的问题的方法是禁用该按钮,直到请求完成。这可以防止用户发送垃圾邮件。你也可以选择做别的事情,而不是像隐藏它那样禁用按钮。
在下面的代码应禁用按钮时AJAX请求开始和重新启用它一旦结束(成功或失败,并不重要)。
您可以参考this page更多的信息有关的事件和handleres发射/与JQuery的Ajax对象访问。
$("form").data("validator").settings.submitHandler =
function(form) {
$.ajax({
method: "PUT",
url: infoGetUrl + itemId,
data: $("form").serialize(),
beforeSend: function() {
disableSendButton();
},
complete: function() {
enableSendButton();
},
success: function() { /* code */ },
error: function(jqXHR, textStatus, errorThrown) { /* code */}
});
};
function disableSendButton()
{
$('input').prop('disabled', true);
}
function enableSendButton()
{
$('input').prop('disabled', false);
}
答
您可以使用“beforeSend”事件调用之前禁用按钮,然后启用它的“成功”事件。
$.ajax({
method: "PUT",
url: infoGetUrl + itemId,
data: $("form").serialize(),
beforeSend: function() {
$('#buttonId').prop('disabled', true);
},
success: function() {
$('#buttonId').prop('disabled', false);
//some code here
},
error: function(jqXHR, textStatus, errorThrown) {
alert("Error during communication with the service, try later");
$('#buttonId').prop('disabled', false);
//some other code
}
});
你现在的代码有什么问题? – Shoe