标签:
MVC校验有两种方法:
方法一:自己动手写js---------略
方法二:
准备工作----导入三个必备的js包
<script src="~/Scripts/jquery-1.7.1.min.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
验证方式:
<head> <meta name="viewport" content="width=device-width" /> <title>Person</title> <script src="~/Scripts/jquery-1.7.1.min.js"></script> <script src="~/Scripts/jquery.validate.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.js"></script> </head> <body> <div> @using (Html.BeginForm("Index", "Home", FormMethod.Post)) { @:姓名:@Html.TextBoxFor(p=>p.Name) @Html.ValidationMessageFor(p=>p.Name)//一定记住绑定确认信息,要不然不显示,建议在文本框之后写,这样提示信息也会在文本框之后显示 <br /> @:年龄:@Html.TextBoxFor(p=>p.Age) @Html.ValidationMessageFor(p=>p.Age) <br /> <input type="submit" /> } </div> </body>
实体类中也要绑定好属性--一般在属性之上写
public class Person { [Required(ErrorMessage="<span style=‘color:red‘>*姓名不能为空</span>")] [StringLength(6, ErrorMessage = "<span style=‘color:red‘>名字长度不能超过六位</span>")] public string Name { get; set; } [Required(ErrorMessage = "<span style=‘color:red‘>*年龄不能为空</span>")] [Range(18, 160, ErrorMessage = "<span style=‘color:red‘>*年龄需在18-160之间</span>")] public int Age { get; set; } }
标签:
原文地址:http://www.cnblogs.com/gchlcc/p/4914539.html