4

在我的 MVC 4 项目中通过 ajax 请求提交表单时,我一直很难让不显眼的验证工作。作为参考,本主题中的人正在做我正在做的几乎相同的事情:

MVC 3 和 JQuery 中的手动表单验证

我经历了那里所做的事情,但我仍然无法让它发挥作用。问题是当我执行 $("#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 });
}
4

4 回答 4

1

您必须将以下脚本添加到您的 _Layout 或视图“jquery.unobtrusive-ajax.js”“jquery.validate.js”“jquery.validate.unobtrusive.js”

于 2015-05-25T22:04:10.510 回答
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 {
    ...
}
于 2013-09-01T10:47:18.410 回答
0

您需要调用.valid()要验证的表单,而不是.validate()方法的结果。

与许多 jQuery 方法不同,.validate()它不适合链接,因为它返回一个类型的对象Validator而不是原始 jQuery 对象(参见:http: //jqueryvalidation.org/validate/

于 2013-07-27T16:37:16.613 回答
0

如果

alert("Is the form valid? " + val.valid());  //Always returns true

关于什么

alert("Is the form valid? " + $("#AddNewClassForm").valid());  // ???

这对我有用...

于 2013-07-27T16:32:40.043 回答