MVC3“不显眼的 JavaScript”模型验证
我曾经这样进行 ajax 调用:
form.bind("submit", function(e) {
e.preventDefault();
form.ajaxSpin("large");
form.ajaxSubmit({
success: function(result) {
if (!b.ajaxFailure(result, true)) {
if(b.validateForm(form,result)) {
console.log(result); // TODO: something?
}
}
},
complete: function() {
form.ajaxSpin(false);
}
});
});
到目前为止,我的设计正在逐步增强。
现在我想在发出实际请求之前在客户端实现模型验证。
我将 jquery.validation.js
插件以及最新的 jquery.validation.unobtrusive.js
脚本添加到项目中。
然后我将代码更改为:
form.validate({
submitHandler: function() {
form.ajaxSpin("large");
form.ajaxSubmit({
success: function(result) {
if (!b.ajaxFailure(result, true)) {
if (b.validateForm(form, result)) {
console.log(result); // TODO: something?
}
}
},
complete: function() {
form.ajaxSpin(false);
}
});
}
});
我认为这将完全相同,除非首先通过验证,否则它不会发出请求。
验证方面工作完美,完全符合预期,使用 mvc 从模型设置到我的视图 DOM 中的数据属性。
失败的部分是我不知道为什么,我又回到了不使用ajax的状态。页面只是重新加载,我的 submitHandler
永远不会触发(与 this 相反链接建议)
我尝试了 submitHandler
的一些其他常见名称(onSuccess
、success
等),但似乎没有一个成为 在职的。
I used to make my ajax calls like this:
form.bind("submit", function(e) {
e.preventDefault();
form.ajaxSpin("large");
form.ajaxSubmit({
success: function(result) {
if (!b.ajaxFailure(result, true)) {
if(b.validateForm(form,result)) {
console.log(result); // TODO: something?
}
}
},
complete: function() {
form.ajaxSpin(false);
}
});
});
so far my design is progressively enhancing.
and now I want to implement model validation on the client-side too, before making an actual request.
I included the jquery.validation.js
plugin to the project, along with the latest jquery.validation.unobtrusive.js
script.
Then I changed my code to:
form.validate({
submitHandler: function() {
form.ajaxSpin("large");
form.ajaxSubmit({
success: function(result) {
if (!b.ajaxFailure(result, true)) {
if (b.validateForm(form, result)) {
console.log(result); // TODO: something?
}
}
},
complete: function() {
form.ajaxSpin(false);
}
});
}
});
which, I figured, would be exactly the same except it wouldn't make requests unless validation got through first.
the validation aspect works perfectly, entirely as expected, using the data attributes mvc sets from the model into my view's DOM.
the part where this fails and I can't figure out why, is that I'm back to not being ajax. the page just reloads, my submitHandler
never fires (contrary to what this link suggests)
I tried a few other common names for the submitHandler
(onSuccess
, success
, etc) but none of them seem to be working.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论