【问题标题】:ASP.Net MVC Ajax form with jQuery validation带有 jQ​​uery 验证的 ASP.Net MVC Ajax 表单
【发布时间】:2010-09-22 20:35:32
【问题描述】:

我有一个 MVC 视图,其中包含使用 Ajax.BeginForm() 辅助方法构建的表单,我正在尝试使用 jQuery Validation plugin 验证用户输入。我让插件突出显示输入数据无效的输入,但尽管输入无效,但表单仍会发布到服务器。

我如何停止这种情况,并确保仅在表单验证时才发布数据?

我的代码


形式:

<fieldset>
    <legend>leave a message</legend>
        <% using (Ajax.BeginForm("Post", new AjaxOptions
           {
               UpdateTargetId = "GBPostList",
               InsertionMode = InsertionMode.InsertBefore,
               OnSuccess = "getGbPostSuccess",
               OnFailure = "showFaliure"
           }))
           { %>
        <div class="column" style="width: 230px;">
            <p>
                <label for="Post.Header">
                    Rubrik</label>
                <%= Html.TextBox("Post.Header", null, new { @style = "width: 200px;", @class="text required" }) %></p>
            <p>
                <label for="Post.Post">
                    Meddelande</label>
                <%= Html.TextArea("Post.Post", new { @style = "width: 230px; height: 120px;" }) %></p>
        </div>
        <p>
            <input type="submit" value="OK!" /></p>
    </fieldset>

JavaScript 验证:

$(document).ready(function() {
    // for highlight
    var elements = $("input[type!='submit'], textarea, select");
    elements.focus(function() {
        $(this).parents('p').addClass('highlight');
    });
    elements.blur(function() {
        $(this).parents('p').removeClass('highlight');
    });

    // for validation
    $("form").validate();   
});

编辑:当我因发布后续问题及其答案中的解决方案而遭到否决时,这也是有效的验证方法...

function ajaxValidate() {
    return $('form').validate({
    rules: {
        "Post.Header": { required: true },
        "Post.Post": { required: true, minlength: 3 }
    },
    messages: {
        "Post.Header": "Please enter a header",
        "Post.Post": {
            required: "Please enter a message",
            minlength: "Your message must be 3 characters long"
            }
        }
    }).form();
}

【问题讨论】:

    标签: jquery asp.net-mvc ajax validation


    【解决方案1】:

    尝试将 OnBegin 回调添加到 AjaxOptions 并从回调中返回 $('form').validate().form() 的值。查看source 看来这应该可行。

    function ajaxValidate() {
       return $('form').validate().form();
    }
    
    <% using (Ajax.BeginForm("Post", new AjaxOptions
           {
               UpdateTargetId = "GBPostList",
               InsertionMode = InsertionMode.InsertBefore,
               OnBegin = "ajaxValidate",
               OnSuccess = "getGbPostSuccess",
               OnFailure = "showFaliure"
           }))
           { %>
    

    EDIT已更新为正确的回调名称。

    【讨论】:

    • OnSubmit 不是 VS intellisense 中的可用选项之一。但是,当使用 OnBegin 时,您的解决方案就像一个魅力。非常感谢您快速正确的回答! =)
    猜你喜欢
    • 2010-10-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多