asp.net-mvc - MVC3 使用 jquery.validate.unobtrusive.js 和 $ ("#form").submit() hijax 不起作用

标签 asp.net-mvc asp.net-mvc-3 jquery unobtrusive-validation

我有一个基本表格

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

相关文章:

asp.net-mvc-3 - 与ASP.NET MVC 3中的 View 页面不同的模型的表单

asp.net-mvc - 将 MVC 网站部署到 Azure

jquery - API:需要 jquery-serialize-object 将表单数据添加到现有数据对象(语义 UI)

javascript - 如何从 MVC 控件中删除验证文本

html - 在 MVC View 中呈现富文本?

asp.net-mvc - HtmlEncode on Post for ASP.Net MVC 3 Html.TextAreaFor

asp.net-mvc - 如何使用 Error.cshtml View 中的过滤器放入 ViewBag 的数据?

javascript - hashchange 上的 Jquery 调用函数

c# - 如何管理 .net 应用程序中的频繁数据访问?

java - 哪个基于 Java 的 MVC 框架与 ASP.NET MVC 最相似?