標籤:
首頁定義驗證實體
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
本文著作權歸作者和部落格園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文串連。
MVC validate.js下使用 ajaxSubmit