标签:
一、添加控制器Home和Model数据
public class UserInfo { public int Id { get; set; } [StringLength(5,ErrorMessage="长度不能大于5")] [Required(ErrorMessage="姓名必填")] public string UserName { get; set; } [RegularExpression(@"^\d+$")] [Range(18, 120)] [Required(ErrorMessage = "*")] public int Age { get; set; } }
public ActionResult Index() {
//可初始化数据 UserInfo userinfo = new UserInfo(); userinfo.UserName = "111"; userinfo.Age = 20; ViewData.Model = userinfo; return View(); }
二、为Index添加视图
<div>
@{ Html.RenderPartial("Add"); }//指向Add视图
</div>
三、添加Add控制器
public ActionResult Add() { return View(); } [HttpPost] public ActionResult Add(UserInfo userinfo) { //ModelState.IsValid=true那么校验就是成功的。 if (ModelState.IsValid) { } return RedirectToAction("Index"); }
四、添加Add视图并创建强类型视图和支架模板
@Html.ValidationSummary(true):
1.input注明要验证是属于前台的,当某各原因导致前台无法进行验证,比如js没有成功加载的,
当后台if (ModelState.IsValid)失败后,错误信息就会显示到 @Html.ValidationSummary()
2.当前后台验证都通过,但某些逻辑验证没有通过,比如用记名密码错误的,可以手工添加错误信息,
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
这个也会显示到@Html.ValidationSummary()
@model MVC自带的校验.Models.UserInfo @{ Layout = null; } <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width" /> <title>Add</title> <script src="~/Scripts/jquery-1.7.1.js"></script> <script src="~/Scripts/jquery.validate.js"></script> <script src="~/Scripts/jquery.validate.unobtrusive.js"></script> </head> <body> @using (Html.BeginForm()) { @Html.ValidationSummary(true) <fieldset> <legend>UserInfo</legend> <div class="editor-label"> @Html.LabelFor(model => model.UserName) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.UserName) @Html.ValidationMessageFor(model => model.UserName) </div> <div class="editor-label"> @Html.LabelFor(model => model.Age) </div> <div class="editor-field"> @Html.TextBoxFor(model => model.Age) @Html.ValidationMessageFor(model => model.Age) </div> <p> <input type="submit" value="Create" /> </p> </fieldset> } <div> @Html.ActionLink("Back to List", "Index") </div> </body> </html>
五、添加校验js文件
<script src="~/Scripts/jquery-1.7.1.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<script src="~/Scripts/jquery.validate.unobtrusive.js"></script>
标签:
原文地址:http://www.cnblogs.com/genesis/p/4882087.html