[英]ASP,NET -MVC5 client-side validation not working
我需要对ASP.NET MVC5应用程序进行客户端验证。 我要实现的是 当用户填写表单中的每个字段时,它会同时进行验证,并随着他/她在表单中输入数据而将字段颜色或边框颜色更改为红色。
我添加了所有要求的详细信息,但是由于某种原因,它没有发生。
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>
<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);
}
由于我要在其中创建表单的页面是局部视图,因此它必须处理的内容与标准视图不同。
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;
}
});
});
我找到了完美解决我问题的解决方案。 在调用$ .validator.unobtrusive.parse之前,请从表单中删除原始验证器和非侵入式验证,如下所示:代码如下:
var form = $("#main_div").closest("form"); form.removeData('validator'); form.removeData('unobtrusiveValidation'); $.validator.unobtrusive.parse(form);
有两种方法。
将您的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验证文件在scripts标签之后呈现。 因此,当您的脚本访问验证功能时,它将给出错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.