一般地,ASP.NET MVC 结合 jQuery Validation 开发,会大大提高页面验证效果,但随着页面增加,每个页面都要写很多javascript脚本,用于触发前端验证。这样的话,很多javascript脚本不利于后期维护,代码有很多重复。
这时候,提供统一触发方法,很有必要,例如:
$(function () {
function ajaxInjection(e) {
var $lever = $(this);
if ($lever.attr("data-ajax-oneoff") != "true" || $lever.attr("data-ajax-executed") != "true") {
var url = $lever.attr("href") || $lever.attr("data-href") || $lever.attr("action");
var pane = $lever.attr("data-ajax-target") || $lever.attr("data-target") || "body";
var load = $lever.attr("data-ajax-loading") || pane;
var form = $lever.is("form") ? this : $lever.attr("data-ajax-form");
var update = $lever.attr("data-update");
var respType = $lever.data("response-content-type") || "html";
if (form) {
var validationInfo = $(form).data("unobtrusiveValidation");
if (validationInfo && validationInfo.validate && !validationInfo.validate()) {
return false;
}
}
if ($lever.data("prevent-default")) {
e.preventDefault();
}
if (respType == "html") {
$(load).loading();
}
$lever.attr("data-ajax-executed", "true");
setTimeout(function () {
var generalWarning = "Operation Failed.";
var generalSucess = "Successfully.";
$.ajaxSetup({ cache: false });
$.ajax({
url: url,
method: form ? "POST" : "GET",
data: form ? $(form).serialize() : null,
success: function (d) {
if (!d) {
$.kendo.warning(generalWarning);
return;
}
if (respType == "json") {
if (d.Ok) {
gridView && gridView.refreshGrid();
$.kendo.success(d.Message || generalSucess);
}
else {
$.kendo.warning(d.Message || generalWarning);
}
}
else {
if (load != pane) {
$(load).hide();
}
$(pane).html(d).show();
}
if (update) {
$(update + "[data-load]").load($(update).attr("data-load"));
}
},
error: function () {
$.kendo.warning(generalWarning);
}
});
}, parseInt($lever.attr("data-ajax-delay") || 0));
}
}
$(document).on("click", "a[data-ajax=diy][href]", ajaxInjection);
$(document).on("click", "button[data-ajax=diy][data-href]", ajaxInjection);
$(document).on("submit", "form[data-ajax=diy][action]", ajaxInjection);
});
<form data-ajax="diy" data-ajax-form="true" data-response-content-type="json" data-prevent-default="true" action="@Url.Action("Save")" method="post" class="form-horizontal">
@Html.HiddenFor(x => x.Id)
<div class="container-fluid pad-15">
<div class="row">
<div class="col-xs-6">
。。。。。。。。。。。。。。。