Model代码:注意其中加了验证
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MvcValidateDemo.Models
{
public class UserInfo
{
public int ID{ get;set; }
[StringLength(5,ErrorMessage="长度必须小于5")]
[Required(ErrorMessage="*姓名必填")]
public string UserName{ get;set; }
[Range(1,100,ErrorMessage="*年龄必须在1-100之间")]
[Required(ErrorMessage = "*年龄必填")]
public int Age { get; set; }
}
}
view视图代码:
@model MvcValidateDemo.Models.UserInfo
@{
Layout = null;
}
<script src="~/Scripts/jquery-1.8.2.js"></script>
<script src="~/Scripts/jquery.validate.js"></script>
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Add</title>
</head>
<body>
@using (Html.BeginForm()) {
@Html.AntiForgeryToken()
@Html.ValidationSummary(true)
<fieldset>
<legend>UserInfo</legend>
<div class="editor-label">
@Html.LabelFor(model => model.UserName)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.UserName)
@Html.ValidationMessageFor(model => model.UserName)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.Age)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Age)
@Html.ValidationMessageFor(model => model.Age)
</div>
<p>
<input type="submit" value="注册" />
</p>
</fieldset>
}
<div>
@Html.ActionLink("Back to List", "Index")
</div>
</body>
</html>
控制器代码:
using MvcValidateDemo.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MvcValidateDemo.Controllers
{
public class UserInfoController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult Add()
{
return View();
}
[HttpPost]
public ActionResult Add(UserInfo uf)
{
if(ModelState.IsValid)
{
return RedirectToAction("index");
}
else
{
return View();
}
}
}
}
在Medol中加入验证方法,在前端即可实现验证功能,提交到控制器的Add(UserInfo userInfo)方法时,在后台判断一下ModelState.IsValid即可,如果为true说明验证通过,返回index视图,如果为false则不通过!返回Add视图!