我有一个基本表格
@Html.ValidationSummary(true)
using (Html.BeginForm("Index", "Home", FormMethod.Post, new { @class = "form" }))
{
<div class="editor-label">
<label for="Name">@Html.LabelFor(model => model.Name)</label>
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
</div>
等等。我的模型正在使用数据注释并且验证已打开。
我使用一些 jquery 来劫持表单:
<script type="text/javascript">
$("form[action='/']").submit(function () {
$.post($(this).attr("action"), $(this).serialize(), function (response) {
$("#contactForm").replaceWith($("#contactForm", response));
});
return false;
});
</script>
如果我正确输入字段并提交,这将起作用。但奇怪的是,如果我在其中一个表单字段中输入无效值,并且验证代码会启动以突出显示我的错误,那么我在上面的 hijaxing 脚本中附加的提交事件函数就会丢失,并且会发生完整的帖子。
关于如何解决这个问题有什么好主意吗?
最佳答案
我认为当您向表单添加提交处理程序时,您将覆盖 jquery 验证/数据注释添加的提交处理程序。
要解决这个问题,您可以添加:
var theForm = $(this);
if ( theForm.valid() ) {
$.post($(this).attr("action"), $(this).serialize(), function (response) {
$("#contactForm").replaceWith($("#contactForm", response));
});
return false;
}
这将确保在发布 POST 之前表单有效。
关于asp.net-mvc - MVC3 使用 jquery.validate.unobtrusive.js 和 $ ("#form").submit() hijax 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7957518/