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 

本文版權歸作者和博客園共有,歡迎轉載,但未經作者同意必須保留此段聲明,且在文章頁面明顯位置給出原文連接。

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM