【问题标题】:MVC3 using jquery.validate.unobtrusive.js and $("#form").submit() hijax not working使用 jquery.validate.unobtrusive.js 和 $("#form").submit() hijax 的 MVC3 不起作用
【发布时间】:2011-10-31 17:47:46
【问题描述】:

我有一个基本表格

@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 脚本中附加的提交事件函数就会丢失,并且会发生完整的帖子。

关于如何解决这个问题有什么好的想法吗?

【问题讨论】:

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


    【解决方案1】:

    我认为,当您向表单添加提交处理程序时,您正在覆盖 jquery 验证/数据注释添加的提交处理程序。

    要解决这个问题,您可以添加:

    var theForm = $(this);
    if ( theForm.valid() ) {
        $.post($(this).attr("action"), $(this).serialize(), function (response) {
            $("#contactForm").replaceWith($("#contactForm", response));
        });
        return false;
    }
    

    这将确保表单在进行 POST 之前有效。

    【讨论】:

    • 谢谢。这似乎确实是个问题。
    • @Dismissile 我没有看到你在哪里挂钩提交?我可能只是错过了一些东西,这是漫长的一天:)
    • @AdamTuliper Dismissile 提供的代码是 Tom Miller 已经拥有的代码的补充。
    猜你喜欢
    • 2016-08-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-23
    相关资源
    最近更新 更多