MVC 模型注解
- 前言:
数据验证分为客户端验证和服务端验证,或两种方式相结合。在客户端验证会减少服务器端的工作量。 - 数据注解和数据验证的关系以及作用:
-
作用:
从数据验证的作用角度来说,数据验证起到很重要的作用,如防止漏洞注入,防止网络攻击,确保数据安全,确保数据合理性,防止垃圾数据等作用 -
分类:
从数据验证的种类来说,一般分为第三方验证,(比如我们用jQuery写好验证插件,在客户端用ajax验证)和基于点内的mvc框架的数据验证
位于服务器端的验证 -
MVC 模型注解定义:
MVC框架提供了数据验证的API,称为”模型数据注解“或”模型元数据“。位于System.ComponentModel.DataAnnotations,使用前需要在Model里引入命名空间。
比如:
密码,必填,且不超过六位:
[Required]
[StringLength(6)]
public string Password {get;set;}
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace jQuery表单验证.Models
{
public class UserInfo
{
[Required]
[StringLength (10,ErrorMessage = "The length is between 4 to 10", MinimumLength =4)]
[Display (Name ="Username")]
//ErrorMsg提示:“Username”字段是必需的,而不是“UserName”字段
public string UserName { get; set; }
[Required]
public string pwd { get; set; }
[Required]
[Compare("Password",ErrorMessage = "Twice input is inconsistent")]
public string comfirmpwd { get; set; }
[Required]
[RegularExpression(@"[A-Za-z0-9._%+_]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,4}")]//{2,4}是长度限制
public string mail { get; set; }
[Required]
[Range(1,100,ErrorMessage = "The input should be between the ages of 1-100")]
public int age { get; set; }
}
}
前端进行数据展示之前,应该用强类型绑定数据模型
<tr>@Html.ValidationMessageFor(t=>t.UserName)</tr>
//为绑定的属性显示错误提示信息
在控制器里,编写方法代码:
using TestDemo.Models
获取前端数据的第三种办法:
public ActionResult Show(UserInfo u)
{
if(ModelState.IsValid)
{
return View("show2",u);
}
return View("index");
}
在show2的视图前端页面里:
@model jQuery表单验证.Models.UserInfo
<p>The input name:@Html.Label("myname",Model.UserName)</p>
<p>The input pwd:@Html.Label("mypwd",Model.pwd)</p>
<p>The input name:@Html.Label("mymail",Model.mail)</p>
<p>The input name:@Html.Label("myage",Model.age.ToString())</p>