Asp.Net MVC 5 Jquery 验证不适用于带有提交事件的 ajax 帖子,显示为有效表单

Posted

技术标签:

【中文标题】Asp.Net MVC 5 Jquery 验证不适用于带有提交事件的 ajax 帖子,显示为有效表单【英文标题】:Asp.Net MVC 5 Jquery validation not working on ajax post with submit event, showing as valid form 【发布时间】:2019-08-10 09:18:03 【问题描述】:

我已添加有关客户端验证的所有必需内容,但验证不起作用。

请帮我找出我错过了什么或做错了什么。

我已经添加了所有需要的东西如下:

BundleConfig.cs

bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
                    "~/Scripts/jquery-version.js"));

bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
                    "~/Scripts/jquery.validate*"));


bundles.Add(new ScriptBundle("~/bundles/bootstrap").Include(
                  "~/Scripts/bootstrap.min.js",
                  "~/Scripts/umd/popper.min.js"));

查看:

@model WebApplication1.Areas.Users.Models.MyViewModel
<div>
    <!-- Modal content-->
    <div class="modal-content">
        @using (html.BeginForm("detail", "mycontroller", null, FormMethod.Post, new  @Id="myForm", @class = "form-horizontal" ))
        
        <!-- Modal Header -->
            <div class="modal-header">
                <h4 class="modal-title">Unit Type</h4>
                <button type="button" class="close" data-dismiss="modal">&times;</button>
            </div>
        <!-- Modal body -->
            <div class="modal-body">
                <div class="full-wdth clearfix otp-section">
                    @Html.AntiForgeryToken()
                    @Html.ValidationSummary(true)
                    @Html.HiddenFor(model => model.Id)
                    <div id="validation-summary"></div>
                    <div class="form-group">
                        @Html.LabelFor(model => model.Name, new  @class = "main-label requiredasterisk" )

                        @Html.TextBoxFor(model => model.Name, htmlAttributes: new  @class = "form-control form-control-sm", placeholder = "Name", maxlength = "50" )
                        @Html.ValidationMessageFor(model => model.Name)
                    </div>
                </div>
            </div>
        <!-- Modal footer -->
            <div class="modal-footer customMargin">
                <button data-dismiss="modal" id="btn-cancel" class="btn btn-default" type="button">Cancel</button>
                <button class="btn btn-primary" id="btn-submit" type="submit">
                    Submit
                </button>
            </div>
        
    </div>
</div>

Layout.cshtml

@Scripts.Render("~/bundles/jquery", "~/bundles/jqueryval", "~/bundles/bootstrap")

WebConfig.cs:

<appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusivejavascriptEnabled" value="true" />
</appSettings>

在显示 JS 文件的浏览器 HTML 页面上:

<script src="/Scripts/jquery-3.3.1.js"></script>
<script src="/Scripts/jquery.validate.js"></script>
<script src="/Scripts/jquery.validate.unobtrusive.js"></script>
<script src="/Scripts/bootstrap.min.js"></script>
<script src="/Scripts/umd/popper.min.js"></script>
<script src="/Scripts/perfect-scrollbar/perfect-scrollbar.min.js"></script>
<script src="/Scripts/XXXXXX.min.js"></script>
<script src="/Scripts/XXXXXXXX.js"></script>

在浏览器上提交 HTML 代码之前:

<div class="form-group">
   <label class="main-label requiredasterisk" for="Name">Name</label>    
   <input class="form-control form-control-sm" data-val="true" data-val-required="The name is required" id="Name" maxlength="50" name="Name" placeholder="Name" type="text" value="">
   <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>

按下提交按钮后:

<div class="form-group">
  <label class="main-label requiredasterisk" for="Name">Name</label>    
  <input class="form-control form-control-sm valid" data-val="true" data-val-required="The name is required" id="Name" maxlength="50" name="Name" placeholder="Name" type="text" value="">
   <span class="field-validation-valid" data-valmsg-for="Name" data-valmsg-replace="true"></span>
</div>

MyViewModel.cs:

public class MyViewModel
            
    /// <summary>
    /// Id 
    /// </summary>
    public int Id  get; set; 

    /// <summary>
    /// name
    /// </summary>
    [Required(ErrorMessage = "The name is required")]
    [Display(Name = "Name")]
    public string Name  get; set;     

jquery:

var BindFormSubmit = function (formControl, options) 
    "use strict";
    var settings = ;
    settings = $.extend(, settings, options);
    formControl.validate(settings.validateSettings);
    formControl.submit(function (e) 
        var formdata = new FormData();         
        $.each(formControl.serializeArray(), function (i, item) 
            formdata.append(item.name, item.value);
        );


        var submitBtn = formControl.find(':submit');
        if (formControl.validate().valid())              
            $.ajax(formControl.attr("action"), 
                type: "POST",
                data: formdata,
                contentType: false,
                processData: false,
                success: function (result) 

                    //on success
                
            );
        
        e.preventDefault();
    );
    return formControl;
;


BindFormSubmit($("#myForm"),  updateTargetId: "validation-summary" );

【问题讨论】:

你是如何渲染模态的?你在用ajax吗?如果你是那么看看这个帖子***.com/questions/23930787/… 您是否检查过是否安装了 Nuget 包? @JonathanOrtega 我已经使用 auth 创建了默认模板应用程序,您能告诉我验证表单需要哪些额外的 Nuget 包吗? @KevDevMan 是的,我正在使用 formElement.validate().valid() 和 formElement.valid() 验证表单,但在这两种情况下它都返回 true(意味着作为有效表单)。 【参考方案1】:

除了将客户端提交事件与验证设置绑定之外,所有事情都是正确的。

因为

formControl.validate(settings.validateSettings);

正在覆盖验证并阻止默认的 MVC 验证,因此,我必须将上面的代码语句注释如下,它将完美运行。

var BindFormSubmit = function (formControl, options) 
    "use strict";
    var settings = ;
    settings = $.extend(, settings, options);
    //formControl.validate(settings.validateSettings);
    formControl.submit(function (e) 
        var formdata = new FormData();         
        $.each(formControl.serializeArray(), function (i, item) 
            formdata.append(item.name, item.value);
        );


        var submitBtn = formControl.find(':submit');
        if (formControl.validate().valid())              
            $.ajax(formControl.attr("action"), 
                type: "POST",
                data: formdata,
                contentType: false,
                processData: false,
                success: function (result) 

                    //on success
                
            );
        
        e.preventDefault();
    );
    return formControl;
;


BindFormSubmit($("#myForm"),  updateTargetId: "validation-summary" );

【讨论】:

以上是关于Asp.Net MVC 5 Jquery 验证不适用于带有提交事件的 ajax 帖子,显示为有效表单的主要内容,如果未能解决你的问题,请参考以下文章

Azure 中的捆绑不适用于 bootstrap 和 jquery、ASP.NET MVC 5

asp.net mvc jquery 下拉验证

ASP.NET MVC 验证不适用于引导模式

ASP.NET MVC 5和jquery ui datepicker验证

ASP.NET MVC 模型验证不适用于控制器构造函数之一

ASP.NET MVC5 JQuery 数据表 CSS 不适用于 Bootstrap Lumen