微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

ASP.NET MVC客户端验证不起作用

如何解决ASP.NET MVC客户端验证不起作用

每当我提交表单时都没有输入必填字段,而不是给出立即的客户端验证错误时,它将使用Httppost Actionresult Index方法允许提交表单。往返服务器端后,出现错误。我添加了对jquery.validate.js,unobtrusive.js两个库的引用,并且还在web.config内将ClientValidationEnabled和UnobtrusiveJavaScriptEnabled值设置为true。 您的亲切帮助将受到高度重视

HTML:

  @model binaryquest.web.CustomModels.ContactVM
@{
    ViewBag.Title = "Home Page";
}

<div id="contact" class="form">
    <div class="container">
        <div class="row">
            <div class="col-lg-12">
                <h2>CONTACT</h2>
                <ul class="list-unstyled li-space-lg">
                    <li class="address">Don't hesitate to give us a call or just use the contact form below</li>
                    
                </ul>
            </div> <!-- end of col -->
        </div> <!-- end of row -->
        <div class="row">
            <div class="col-lg-8 offset-lg-2">

                <!-- Contact Form -->
                
                <form action="/Home/Index" method="post">
                    @Html.AntiForgeryToken()
                    @Html.ValidationMessage("expired",new { @class = "text-danger" })
                    @Html.ValidationMessage("CaptchaFail",new { @class = "text-danger" })

                    <div class="form-group">
                        @Html.LabelFor(model => model.Name,htmlAttributes: new { @class = "required" })
                        @Html.EditorFor(model => model.Name,new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Name,"",new { @class = "text-danger" })
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Email,htmlAttributes: new { @class = "required" })
                        @Html.EditorFor(model => model.Email,new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Email,new { @class = "text-danger" })
                    </div>

                    <div class="form-group">
                        @Html.LabelFor(model => model.Message,htmlAttributes: new { @class = "required" })
                        @Html.EditorFor(model => model.Message,new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Message,new { @class = "text-danger" })
                    </div>

                    <div class="form-group checkBox">
                        <input type="checkBox" id="cterms" value="Agreed-to-Terms" required>I have read and agree to Leno's stated conditions in <a href="/Home/PrivacyPolicy">Privacy Policy</a>.
                        <div class="help-block with-errors"></div>
                    </div>

                    @Html.CheckBoxFor(model => model.IsTermsAccepted,new { htmlAttributes = new { @class = "form-control" } })
                    @Html.LabelFor(model => model.IsTermsAccepted,htmlAttributes: new { @class = "required" })
                    @Html.ValidationMessageFor(model => model.IsTermsAccepted,new { @class = "text-danger" })

                    <div class="form-group">
                        <button type="submit" class="form-control-submit-button">SUBMIT MESSAGE</button>
                    </div>

                    <div class="form-message">
                        <div id="cmsgSubmit" class="h3 text-center hidden"></div>
                    </div>

                </form>
                <!-- end of contact form -->

            </div> <!-- end of col -->
        </div> <!-- end of row -->
    </div> <!-- end of container -->
</div>

@section scripts{

    
    <script src="//ajax.aspnetcdn.com/ajax/jquery.validate/1.13.1/jquery.validate.js"></script>
    <script src="//ajax.aspnetcdn.com/ajax/mvc/5.2.3/jquery.validate.unobtrusive.js"></script>

    
}

型号:

public class ContactVM
    {
        [required(ErrorMessage = "You must provide Name")]
        [displayName("Name")]
        public string Name { get; set; }

        
        [required(ErrorMessage = "You must provide an Email address")]
        [displayName("Email")]
        [EmailAddress]
        public string Email { get; set; }

        [required(ErrorMessage = "You must provide Message")]
        [displayName("Your Message")]
        public string Message { get; set; }


        [display(Name = "Terms and Conditions")]
        [Range(typeof(bool),"true",ErrorMessage = "You must accept the terms and conditions!")]
        public bool IsTermsAccepted { get; set; }
        
        

    }

控制器:

            public ActionResult Index()
            {
                return View();
            }

            [HttpPost]
            [AllowAnonymous]
            [ValidateAntiForgeryToken]
            public ActionResult Index(ContactVM model)
            {
               
                string sendGridKey ="";
                if (ModelState.IsValid)
                {
                    SendMail(model,sendGridKey);
                    return RedirectToAction("Thanks","Home");
                }
    
                return View(model);
            }

解决方法

您需要使用已加载的javascript。在您的视图中添加以下内容:

<script>
$(document).ready(function() {
   $.validator.unobtrusive.parse($("#myForm"));
}

function onSubmit(e) {
  $("#myForm").validate(); // this will validate the form and show the validation messages
  if($("#myForm").valid()) {
     $("#myForm").submit(); // submits the form
  }
  // stop the postback
  e.preventDefault();
}
</script>

然后在表单元素上:

<form id="myForm" onsubmit="onSubmit();" action="/Home/Index">
,

似乎未加载验证脚本。您是否已加载_layout.cshtml?

@RenderSection("scripts",required: false)

并尝试在表单开始处添加验证摘要

@Html.ValidationSummary(true,"",new { @class = "text-danger" })
,

在服务器端验证中,必须通过回发提交页面才能在服务器上进行验证,如果模型数据无效,则服务器将通过客户端验证将响应发送回客户端,即输入数据在提交后立即进行检查,因此不会回发到服务器,也不会刷新页面。 https://www.c-sharpcorner.com/UploadFile/3d39b4/Asp-Net-mvc-client-side-validation/

,

您可以在下面访问此链接

https://www.tutorialsteacher.com/articles/enable-client-side-valiation-in-mvc

@Scripts.Render("~/bundles/jquery")
@Scripts.Render("~/Scripts/jquery.validate.min.js")
@Scripts.Render("~/Scripts/jquery.validate.unobtrusive.min.js")

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。