ASP.NET MVC5验证系列之服务端验证(2)

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>

ASP.NET MVC5验证系列之服务端验证

首先验证,都为空的情况:

ASP.NET MVC5验证系列之服务端验证

Name不为空,Email为空

ASP.NET MVC5验证系列之服务端验证

Name不为空,Email输入非法格式数据

ASP.NET MVC5验证系列之服务端验证

两个都输入合法的数据:

ASP.NET MVC5验证系列之服务端验证

好了,以上就是MVC中服务端验证了,我们一般是使用第二种,来进行验证。也就是数据注解。

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wjyfdw.html