在我的MVC 4项目中通过ajax请求提交表单时,我一直很难获得不显眼的验证。作为参考,本主题中的人正在做我正在做的几乎相同的事情:
Manual form validation in MVC 3 and JQuery
我经历了那里所做的事情,但我仍然无法让它发挥作用。问题是,当我执行$(“#Form”)。valid()时,它总是返回true,即使我发送请求,模型也无效。我在我的捆绑包中设置了相应的脚本,但我无法获得正确验证客户端的表单。如何正确验证?我认为一旦数据注释被设置,它就“应该工作”,但这显然不是这种情况。
此外,此特定表单也在部分视图的Kendo UI窗口中加载了jQuery。看完这篇文章后的答案:Asp MVC unobtrusive Client Validation always returning true使用表单id作为选择器,而.valid()仍然返回true,但Class Name为false。但是,guid semester 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 });
}
答案 0 :(得分:1)
您必须将以下脚本添加到_Layout或视图“jquery.unobtrusive-ajax.js” “jquery.validate.js” “jquery.validate.unobtrusive.js”
答案 1 :(得分:0)
如果
alert("Is the form valid? " + val.valid()); //Always returns true
怎么样?
alert("Is the form valid? " + $("#AddNewClassForm").valid()); // ???
这对我有用......
答案 2 :(得分:0)
您需要在要验证的表单上调用.valid()
,而不是.validate()
方法的结果。
与许多jQuery方法不同,.validate()
不适合链接,因为它返回类型为Validator
的对象而不是原始jQuery对象(请参阅:http://jqueryvalidation.org/validate/)
答案 3 :(得分:0)
此扩展程序适用于我:
$(document).ready(function () {
jQuery.noConflict();
// if the form is in a dialog box {
var form = $('#formCreateRequest');
form
.removeData('validator')
.removeData('nobtrusiveValidation');
$.validator.unobtrusive.parse(form); // }
$.fn.extend({
// form validation {
isValid: function () {
var self = $(this);
$.validator.unobtrusive.parse(self);
return self.data('unobtrusiveValidation').validate();
} // }
});
});
使用:
if ($('#formId').isValid()) {
...
} else {
...
}