MVC validate.js下使用 ajaxSubmit
首页定义验证实体
using System.ComponentModel.DataAnnotations; using System.Web.Mvc; namespace MvcApplication1.Models { public class Student { [Display(Name = "名称")] [Required(AllowEmptyStrings = false, ErrorMessage = "输入名称")] public string Name { get; set; } [Display(Name = "Age")] [Required(AllowEmptyStrings = false, ErrorMessage = "输入年龄")] [Remote("CheckAge", "Home")] public int Age { get; set; } } }
编写Controller
using MvcApplication1.Models; using System.Web.Mvc; namespace MvcApplication1.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } [HttpPost] public ContentResult Index(Student student) { return Content("success"); } public JsonResult CheckAge(int age) { if (age < 18) { return Json(true, JsonRequestBehavior.AllowGet); } return Json("Error", JsonRequestBehavior.AllowGet); } } }
前端
@model MvcApplication1.Models.Student @{ ViewBag.Title = "index"; } <h2>index</h2> <script src="~/script/jquery.min.js"></script> <script src="~/script/jquery.validate.min.js"></script> <script src="~/script/jquery.validate.unobtrusive.min.js"></script> <script src="~/script/jquery.form.js"></script> @using (Html.BeginForm(null, null, FormMethod.Post, new { name = "from1", id = "from1" })) { @Html.TextBoxFor(model => model.Name) @Html.ValidationMessageFor(model => model.Name) @Html.TextBoxFor(model => model.Age) @Html.ValidationMessageFor(model => model.Age) <input type="submit" value="提交" id="js_button" /> }
采用Mvc + jquery.validate.js 验证好处:
1.快速开发
2.支持后台验证 [Remote("CheckAge", "Home")]
3.不用在脚本中写入验证规rules如:
$("#from1").validate({ rules: { Name: { required: true, maxlength: 10 }, Age: { required: true, maxlength: 10 } } });
实现Ajax
网上查找基本上都是
$(document).ready(function () { $("#from1").validate({ submitHandler: function (form) { form.submit(); } }) })
但是此方法根本就不能进入,因为jquery.validate.unobtrusive.min.js已经重写了jquery.validate.min.js的validate方法
看了源码
b.valid() b是个form 所以果断修改验证代码如下,亲测成功。
帮你们解决问题的,点个赞
作者:释迦苦僧 出处:http://www.cnblogs.com/woxpp/p/5791296.html
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接。
生活不易,五行缺金,求打点
![](http://files.cnblogs.com/files/woxpp/QQ%E6%88%AA%E5%9B%BE20161229110254.bmp)