简体   繁体   English

MVC4客户端验证和ajax

[英]MVC4 client side validation and ajax

Answer: 回答:

OK answer supplied below, by @www.innovacall.com is correct, I just didn't read it right the first time, now it works perfectly, thanks. 下面提供的确定答案,@ www.innovacall.com是正确的,我只是第一次没有正确阅读,现在它完美无缺,谢谢。

Original question: 原始问题:

I tried some solutions but none works for me. 我尝试了一些解决方案,但没有一个适合我。

In my project, I got a modal popup like this (I use bootstrap): 在我的项目中,我得到了一个这样的模态弹出窗口(我使用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 -->

I submit data from that popup with the following ajax: 我使用以下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();
        }
    });
});

The problem: 问题:

Standard @Html.ValidationSummary() helper inside the View rendered in my modal popup, is not being called - thus I have no client side validation. 在我的模态弹出窗口中呈现的View中的标准@ Html.ValidationSummary()帮助器未被调用 - 因此我没有客户端验证。 I know that @Html.ValidationSummary() only works when I use @Html.BeginForm(...) but how can I validate my ajax before submit? 我知道@ Html.ValidationSummary()仅在我使用@ Html.BeginForm(...)时才有效,但如何在提交之前验证我的ajax? I tried something like this: 我试过这样的事情:

$("#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();
        }
    });
});

But it's not working, that is: there are no errors, but when I debug the JS, it sort of "skips" the validation, neither submitHandler nor showErrors is being hit... 但是它不起作用,那就是:没有错误,但是当我调试JS时,它会“跳过”验证,但是commitHandler和showErrors都没有被击中......

How can I validate my form before ajax call? 如何在ajax调用之前验证我的表单?

Best regards. 最好的祝福。

EDIT1: EDIT1:

@www.innovacall.com: @ www.innovacall.com:

I tried this approach but still it is not working for some reason... 我试过这种方法,但由于某些原因它仍然无法工作......

My _AddSkillAnswer partial looks like this: 我的_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")
}

I tried the following combinations: 我尝试了以下组合:

$("#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();
        }
    });
});

and this: 和这个:

$("#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();
        }
    });
});

but still it doesn't work, neither submitHandler nor showErrors is being hit. 但它仍然无法正常工作,提交者和showErrors都没有被击中。

If you loaded your form with ajax, you need to parse your form again : 如果您使用ajax加载表单,则需要再次解析表单:

$.validator.unobtrusive.parse(form);
form.validate();
if (form.valid()) {
    form.submit();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM