ASP,NET -MVC5客户端验证不起作用

时间:2015-06-30 11:37:49

标签: javascript c# asp.net-mvc razor client-side-validation

我需要为ASP.NET MVC5应用程序进行客户端验证。我想要实现的是;当用户填写表单中的每个字段时,验证其相同的时间,并将字段颜色或边框颜色更改为红色,因为他/她将使用表单中的数据输入。

我已添加所有需求详情但由于某种原因没有发生;

bundleConfig

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

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

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

主页面布局

我在html标题中添加了jquery为;

<!DOCTYPE html>
<html>
<head>
   <meta charset="utf-8" />
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <title>@ViewBag.Title</title>
              @Styles.Render("~/Content/css")
              @Styles.Render("~/Content/themes/base/ThemeCSS")
              @Scripts.Render("~/bundles/modernizr")
              @Scripts.Render("~/bundles/jquery")
  </head>
  <body>
      //my other code....
      //at bottom

  @Scripts.Render("~/bundles/bootstrap")
  @Scripts.Render("~/bundles/jqueryui")
  @Scripts.Render("~/bundles/jqueryval")
  @Scripts.Render("~/bundles/DefaultThemeScripts")
  @RenderSection("scripts", required: false)
 </body>
</html>

学生模型课

这是表单模型类

public class Student
{
    public Student(){}

    [Key]
    [Display(Name="Student ID")]
    public int StudentID { get; set; }

    [Display(Name = "Student UWL ID")]
    [Required(ErrorMessage="Require Your Student UWL ID")]
    [Range(0, Int32.MaxValue, ErrorMessage = "Only Number Allowed")]
    public int StudentNumber_UWLID { get; set; }

    [StringLength(50)]
    [Required(ErrorMessage = "Required Title")]
    [Display(Name = "Title")]
    public string Title { get; set; }

    [StringLength(50)]
    [Display(Name = "Other Title")]
    public string OtherTitle { get; set; }

    [StringLength(50)]
    [Required(ErrorMessage = "Required Gender")]
    [Display(Name = "Gender")]
    public string Gender { get; set; }

    [StringLength(250)]
    [Required(ErrorMessage = "Required First Name")]
    [Display(Name = "First Name")]
    public string FirstName { get; set; }

    [StringLength(250)]
    [Display(Name = "Middle Name")]
    public string MiddleName { get; set; }

    [StringLength(250)]
    [Required(ErrorMessage = "Required Last Name")]
    [Display(Name = "Last Name")]
    public string LastName { get; set; }

    [StringLength(250)]
    [Required(ErrorMessage = "Required Nationality")]
    [Display(Name = "Nationality")]
    public string Nationality { get; set; }

    [StringLength(250)]
    [Required(ErrorMessage = "Required Your Date Of Birth")]
    [Display(Name = "Date Of Birth")]
    public System.DateTime DateOfBirth { get; set; }
 }

剃刀形式

@model App.DAL.Model.Student

<script type="text/javascript">

$('#CreateStudentProfileForm').submit(function (e) {

    e.preventDefault();

    var formURL = $(this).attr("action");
    $ajax({.....
   )};
 </script>


@using (Html.BeginForm("CreateStudentProfile", "StudentProfile", FormMethod.Post, new { id = "CreateStudentProfileForm" }))

{
   @Html.AntiForgeryToken()

<div class="form-horizontal">
    <h4>Student</h4>
    <hr />
    @Html.ValidationSummary(true, "", new { @class = "text-danger" })
    <div class="form-group">
        @Html.LabelFor(model => model.StudentNumber_UWLID, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.StudentNumber_UWLID, new { htmlAttributes = new { id = "StudentNumber_UWLID", @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.StudentNumber_UWLID, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Title, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Title, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Title, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.OtherTitle, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.OtherTitle, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.OtherTitle, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Gender, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Gender, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Gender, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.FirstName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.FirstName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.FirstName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.MiddleName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.MiddleName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.MiddleName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.LastName, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.LastName, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.LastName, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.Nationality, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.Nationality, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.Nationality, "", new { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        @Html.LabelFor(model => model.DateOfBirth, htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.EditorFor(model => model.DateOfBirth, new { htmlAttributes = new { @class = "form-control datepicker" } })
            @Html.ValidationMessageFor(model => model.DateOfBirth, "", new  { @class = "text-danger" })
        </div>
    </div>

    <div class="form-group">
        <div class="col-md-offset-2 col-md-10">
            <input type="submit" value="Create" class="btn btn-default" />
        </div>
    </div>
</div>
}

<div>
     @Html.ActionLink("Back to My Profile Home Page", "MyProfile")
</div>

的Web.config

 <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>

控制器类

  [HttpGet]
    public ActionResult CreateStudentProfile()
    {
        return PartialView("CreateStudentProfile_Partial");
    }

    [HttpPost]
    public ActionResult CreateStudentProfile(Student _studentModel)
    {
        try
        {
            if(ModelState.IsValid)
            {
               int _entityID =  _studentProfileServices.CreateNewStudentProfile(_studentModel);

               if (_entityID != 0) 
               {
                   return Json(new { Response = "Success" });
               }
               else
               {
                   return Json(new { Response = "Error" });
               }
            }
            else
            {
                return Json(new { Response = "Invalid Entry" });
            }
        }
        catch (DataException ex)
        {
            ModelState.AddModelError("", "Unable To Create New Student Profile" + ex);
        }

        return PartialView("CreateStudentProfile_Partial", _studentModel);
    }

3 个答案:

答案 0 :(得分:1)

As My pages where I am creating form are partial view so it has to handle differently then the standard view.. I have found solution in do my research on google as following;

http://code.davidferguson.me.uk/post/47540738095/mvc-client-validation-after-partialview-loaded-via

//this code goes in your partialview
$(function(){ 
   //allow the validation framework to re-prase the DOM
   jQuery.validator.unobtrusive.parse(); 

   jQuery.validator.unobtrusive.parse("#formId");
 });

//...

$(function(){
$("#SubmitButton").click(function(){ 
  if (!$("#Form1").valid()){ 
    return false; 
   } 
 });
});

答案 1 :(得分:0)

我找到了一个解决方案,完美解决了我的问题。 在调用$ .validator.unobtrusive.parse之前,从表单中删除原始验证器和不显眼的验证,如下所示: 下面是代码:

var form = $("#main_div").closest("form");
form.removeData('validator');
form.removeData('unobtrusiveValidation');
$.validator.unobtrusive.parse(form);
您应该参考的详细信息here

答案 2 :(得分:-1)

有两种方法。

JqueryVal脚本捆绑之后,将Jquery捆绑包放在上面。 像

 @Styles.Render("~/Content/css")
 @Styles.Render("~/Content/themes/base/ThemeCSS")
 @Scripts.Render("~/bundles/modernizr")
 @Scripts.Render("~/bundles/jquery")
 @Scripts.Render("~/bundles/jqueryval")

或在脚本部分编写脚本

@section scripts
{
    // write scripts here
}

原因是,您的jquery验证文件在脚本标记后呈现。因此,当您的脚本访问验证功能时,它将给出错误。