在我的 MVC 4 项目中通过 ajax 请求提交表单时,我一直很难让不显眼的验证工作。作为参考,本主题中的人正在做我正在做的几乎相同的事情:
我经历了那里所做的事情,但我仍然无法让它发挥作用。问题是当我执行 $("#Form").valid() 时,它总是返回 true,即使我发送请求,模型也是无效的。我在我的包中设置了适当的脚本,但我无法让表单正确验证客户端。我怎样才能使它正确验证?我认为一旦设置了数据注释,它就“应该可以工作”,但显然情况并非如此。
此外,这个特殊的表单也正在从局部视图中的 Kendo UI 窗口中加载 jQuery。查看这篇文章的答案后:Asp MVC unobtrusive Client Validation always return true doing using the form id as selector and .valid() still return true, but Class Name is false。但是,guid 学期 ID 返回 true。
我的代码如下:
模型
public class Class
{
public Class()
{
ClassId = Guid.NewGuid();
}
[Key]
public Guid ClassId { get; set; }
[Display(Name = "Class Name")]
[Required(ErrorMessage = "A Class Name is required.")]
public string ClassName { get; set; }
public int UserId { get; set; }
[Display(Name = "Term Type")]
[Required(ErrorMessage = "The Term Type is required.")]
public Guid SemesterId { get; set; }
[ForeignKey("SemesterId")]
public virtual Semester Semester { get; set; }
[Display(Name = "Class Year")]
public int Year { get; set; }
[Display(Name = "Has Weighted Grades?")]
public bool HasWeightedGrades { get; set; }
public virtual List<Grade> Grades { get; set; }
}
形式
@using (Html.BeginForm("AddClass", "", FormMethod.Post, new { name = "AddNewClassForm", id = "AddNewClassForm" }))
{
<div>
<div>@Html.LabelFor(m => m.ClassName)</div>
<div>
@Html.TextBoxFor(m => m.ClassName, new { @class = "input-xlarge" })
@Html.ValidationMessageFor(m => m.ClassName)
</div>
<div>@Html.LabelFor(m => m.SemesterId)</div>
<div>
@Html.DropDownList("SemesterId", null, "-- Select a Term Type --", new { @class = "input-xlarge" })
@Html.ValidationMessageFor(m => m.SemesterId)
</div>
</div>
}
<div>
<button id="AddClassButton" class="btn btn-primary" type="submit"><i class="icon-plus icon-white"></i> Add Class</button>
<button id="CancelAddClassButton" class="btn btn-danger" type="submit"><i class="icon-ban-circle icon-white"></i> Cancel</button>
</div>
jQuery 事件
//================================================================================================================================
// AddClassButton: Click event handlers.
//================================================================================================================================
$('#AddClassButton').unbind('click').bind('click', function (e) {
$.validator.unobtrusive.parse($('#AddClassWindow'));
var val = $("#AddNewClassForm").validate();
val.showErrors();
alert("Is the form valid? " + val.valid()); //Always returns true
alert("Is Class Name Valid? " + $("#ClassName").valid()); //Still returns true
alert("Is Semester Id Valid? " + $("#SemesterId").valid()); //Still returns true
e.preventDefault(); // Prevent this from doing default (possibly submit form).
e.stopPropagation(); // Prevent infinite loop.
});
捆绑
bundles.Add(new ScriptBundle("~/bundles/jqueryval").Include(
"~/Scripts/jquery.unobtrusive*",
"~/Scripts/jquery.validate*"));
//Ignoring these so only the min.js versions get rendered
bundles.IgnoreList.Ignore("jquery.validate.js");
bundles.IgnoreList.Ignore("jquery.validate.unobtrusive.js");
bundles.IgnoreList.Ignore("jquery.unobtrusive-ajax.js");
控制器动作
[Authorize]
public ActionResult AddClass()
{
var userName = User.Identity.Name;
var userProfile = db.UserProfiles.SingleOrDefault(x => x.UserName == userName);
InitializeSemesters();
InitializeYears();
return PartialView(new Class() { UserId = userProfile.UserId, Year = DateTime.Now.Year });
}