MVC4客户端验证和ajax

时间:2014-02-11 14:14:11

标签: javascript jquery ajax asp.net-mvc-4 twitter-bootstrap

答案:

@ www.innovacall.com下面提供的正确答案是正确的,我刚刚第一次没看错,现在它完美无缺,谢谢。

原始问题:

我尝试了一些解决方案,但没有一个适合我。

在我的项目中,我得到了一个这样的模态弹出窗口(我使用bootstrap):

<!-- Modal -->
<div class="modal fade" id="skillAnswerModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button>
        <h4 class="modal-title" id="myModalLabel">@ViewBag.AddressTimeTableMapModalEditHeaderTitle</h4>
      </div>
      <div class="modal-body">
        <div id="addSkillAnswerModal">
            @Html.Partial("_AddSkillAnswer", Model.TempSkillAnswer)
        </div>
      </div>
      <div class="modal-footer">
        <button type="button" class="btn btn-default" data-dismiss="modal">@ViewBag.CloseButtonLabel</button>
        <button type="button" class="btn btn-primary" id="btnAddSkillAnswerModal" >@ViewBag.SaveChangesButtonLabel</button>
      </div>
    </div><!-- /.modal-content -->
  </div><!-- /.modal-dialog -->
</div><!-- /.modal -->

我使用以下ajax从该弹出窗口提交数据:

$("#btnAddSkillAnswerModal").click(function () {
    $.ajax({
        url: addSkillUrl,
        type: "POST",
        cache: false,
        async: true,
        traditional: true,
        data: $("#addSkillAnswerModal :input").serialize(),
        dataType: "json",

        success: function (result) {
            $("#skillAnswerModal").modal('toggle');
            $("#addSkillAnswerModal input[type!=hidden]").val('');
            $("#IsAnswerVisible").val("true");

            oTable.fnReloadAjax();
        }
    });
});

问题:

标准@ Html.ValidationSummary()帮助器在我的模态弹出窗口中呈现的视图中没有被调用 - 因此我没有客户端验证。我知道@ Html.ValidationSummary()仅在我使用@ Html.BeginForm(...)时才有效,但如何在提交之前验证我的ajax?我试过这样的事情:

$("#btnAddSkillAnswerModal").click(function () {
    $("#AddSkillAnswerForm").validate({
        debug: true,
        submitHandler: function (form) {
            $.ajax({
                url: addSkillUrl,
                type: "POST",
                cache: false,
                async: true,
                traditional: true,
                data: $("#addSkillAnswerModal :input").serialize(),
                dataType: "json",

                success: function (result) {
                    $("#skillAnswerModal").modal('toggle');
                    $("#addSkillAnswerModal input[type!=hidden]").val('');
                    $("#IsAnswerVisible").val("true");

                    oTable.fnReloadAjax();
                }
            });
        },

        showErrors: function (errorMap, errorList) {
            $("#summary").html("Your form contains "
            + this.numberOfInvalids()
            + " errors, see details below.");
            this.defaultShowErrors();
        }
    });
});

但是它不起作用,那就是:没有错误,但是当我调试JS时,它会“跳过”验证,并且commitHandler和showErrors都没有被点击......

如何在ajax调用之前验证我的表单?

最好的问候。

EDIT1:

@ www.innovacall.com:

我尝试过这种方法,但由于某些原因它仍无法正常工作......

我的_AddSkillAnswer部分看起来像这样:

@model HostessServiceApplication.WebUI.Models.Admin.AgencyAnimatorSkillAnswerListAddSkillAnswer

@using HostessServiceApplication.Common.Localizer
@using HostessServiceApplication.WebUI.Resources
@using HostessServiceApplication.WebUI.Resources.Admin

@{
    Layout = null;

    //GlobalResources:
    var globalLocalizer = new UniversalTextLocalizer(typeof(TranslationStrings));
    ViewBag.SaveChangesButtonLabel = globalLocalizer.GetTranslatedVariable("SaveChangesButtonLabel");

    var viewSpecificLocalizer = new UniversalTextLocalizer(typeof(AddSkillAnswer));

    ViewBag.Title = viewSpecificLocalizer.GetTranslatedVariable("AddSkillAnswerPageTitle");
}

<h2>@ViewBag.Title</h2>

@using (Html.BeginForm("AddSkillAnswer", "Admin", FormMethod.Post, new { enctype = "multipart/form-data" ,id="AddSkillAnswerForm"}))
{
    @Html.AntiForgeryToken()
    @Html.ValidationSummary()

    @Html.EditorForModel("Admin/AgencyAnimatorSkillAnswerListAddSkillAnswer")
}

我尝试了以下组合:

$("#btnAddSkillAnswerModal").click(function () {
    var form = $("#AddSkillAnswerForm");

    $.validator.unobtrusive.parse(form);
    //form.validate();
    form.validate({
        debug: true,
        submitHandler: function (form) {
            $.ajax({
                url: addSkillUrl,
                type: "POST",
                cache: false,
                async: true,
                traditional: true,
                data: $("#addSkillAnswerModal :input").serialize(),
                dataType: "json",

                success: function (result) {
                    $("#skillAnswerModal").modal('toggle');
                    $("#addSkillAnswerModal input[type!=hidden]").val('');
                    $("#IsAnswerVisible").val("true");

                    oTable.fnReloadAjax();
                }
            });
        },

        showErrors: function (errorMap, errorList) {
            $("#summary").html("Your form contains "
    + this.numberOfInvalids()
    + " errors, see details below.");
            this.defaultShowErrors();
        }
    });
});

和此:

$("#btnAddSkillAnswerModal").click(function () {
    var form = $("#AddSkillAnswerForm")
    .removeData("validator") /* added by the raw jquery.validate plugin */
    .removeData("unobtrusiveValidation");  /* added by the jquery unobtrusive plugin */

    $.validator.unobtrusive.parse(form);
    form.validate({
        debug: true,
        submitHandler: function (form) {
            $.ajax({
                url: addSkillUrl,
                type: "POST",
                cache: false,
                async: true,
                traditional: true,
                data: $("#addSkillAnswerModal :input").serialize(),
                dataType: "json",

                success: function (result) {
                    $("#skillAnswerModal").modal('toggle');
                    $("#addSkillAnswerModal input[type!=hidden]").val('');
                    $("#IsAnswerVisible").val("true");

                    oTable.fnReloadAjax();
                }
            });
        },

        showErrors: function (errorMap, errorList) {
            $("#summary").html("Your form contains "
    + this.numberOfInvalids()
    + " errors, see details below.");
            this.defaultShowErrors();
        }
    });
});

但它仍然不起作用,也没有提交commitHandler和showErrors。

1 个答案:

答案 0 :(得分:2)

如果您使用ajax加载表单,则需要再次解析表单:

$.validator.unobtrusive.parse(form);
form.validate();
if (form.valid()) {
    form.submit();
}
相关问题