using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; namespace Server_Side_Validation_IN_MVC.Models { public class StudentServer { [Required(ErrorMessage="Name为必填项")] public string Name { get; set; } [Required(ErrorMessage="电子邮件必须")] [EmailAddress(ErrorMessage="电子邮件格式不对")] public string Email { get; set; } } }
在控制器中新建两个方法:
public ActionResult SeverSideIndex() { return View(); } [HttpPost] public ActionResult SeverSideIndex(StudentServer model) { if (ModelState.IsValid) { ViewBag.Name = model.Name; ViewBag.Email = model.Email; } return View(); }
对应的视图:
@model Server_Side_Validation_IN_MVC.Models.StudentServer
@{
Layout = null;
}
@if (ViewData.ModelState.IsValid)
{
if (ViewBag.Name != null)
{
<b>
Name:@ViewBag.Name<br />
Email:@ViewBag.Email
</b>
}
}
<!DOCTYPE html>
<html>
<head>
<meta content="width=device-width" />
<title>SeverSideIndex</title>
</head>
<body>
<div>
@using (Html.BeginForm())
{
@Html.ValidationSummary(true)
<fieldset>
<legend>Student</legend>
<div>
@Html.LabelFor(model=>model.Name)
</div>
<div>
@Html.EditorFor(model=>model.Name)
@Html.ValidationMessageFor(model=>model.Name)
</div>
<div>
@Html.LabelFor(model => model.Email)
</div>
<div>
@Html.EditorFor(model => model.Email)
@Html.ValidationMessageFor(model => model.Email)
</div>
<p>
<input type="submit" value="Create"/>
</p>
</fieldset>
}
</div>
</body>
</html>
首先验证,都为空的情况:
Name不为空,Email为空
Name不为空,Email输入非法格式数据
两个都输入合法的数据:
好了,以上就是MVC中服务端验证了,我们一般是使用第二种,来进行验证。也就是数据注解。