1场景 某一天我在教我学生搭建Asp.net 框架做项目的时候 发现做一个登录 后台模型验证需要用到验证“用户名”和“密码”不能为空。 然后我建立了一个模型 带有这两个字段非空的特性
后面我学生问我老师如果我要修改用户信息的时候不需要验证用户名和密码为空 这刚才的模型好像不能用 后台还是会验证用户名和密码不能为空
后来我给他解释的是 最好一个action 接受数据的模型 用一个model 也就是说登录 用一个模型 修改密码 用一个模型 添加和修改用户信息用一个模型
如此本质上对我们用户信息表的操作根据UI的业务操作要添加好几个模型
后面我查找了很多资料 也没找到合适的第三方模型验证框架 可以给模型字段添加特性的验证 但是可以根据action 动作来使部分特性生效。于是我自己把模型验证的特性类做了重新。代码如下 希望对大家有所帮助。
代码如下
Code:1
namespace MVC_GaoJi
{
public class MyValidateHelper
{
///
/// 当前请求Action 是否包含指定验证类型
///
///
public bool IsContainsOperationType(string validateOperationType)
{
bool flag = false;
foreach (string item in validateOperationType.Split(’|’))
{
if (GetCurrentActionOperationType().Contains(item))
{
flag = true;
break;
}
}
return flag;
}
/// <summary>
/// 当前请求Action的方法里是所有的验证操作类型
/// </summary>
/// <returns></returns>
public List<string> GetCurrentActionOperationType()
{
List<string> Operation = new List<string>();
//得到当前Controller
string controllerName = System.Web.HttpContext.Current.Request.RawUrl.Split('/')[1];
//得到当前Action
string actionName = System.Web.HttpContext.Current.Request.RawUrl.Split('/')[2];
if (!string.IsNullOrEmpty(controllerName) && !string.IsNullOrEmpty(actionName))
{
//反射加载控制器类
Type type = Type.GetType("MVC_GaoJi.Controllers." + controllerName + "Controller");
//加载Action的方法
MethodInfo method = type.GetMethod(actionName);
//获取方法里面所有的OperationTypeAttribute 特性类
object[] attributes = method.GetCustomAttributes(typeof(ValidateOperationTypeAttribute), true);
if (attributes.Any())
{
//迭代特性类里面的所有属性
foreach (object item in attributes)
{
PropertyInfo pi = item.GetType().GetProperties().FirstOrDefault(x => x.Name == "OperationType");
if (pi != null)
{
Operation.Add(pi.GetValue(item, null).ToString());
}
}
}
}
return Operation;
}
}
}
Code:2
public class ValidateOperationTypeAttribute : Attribute
{
public string OperationType { get; set; }
public ValidateOperationTypeAttribute(string operationType)
{
this.OperationType = operationType;
}
}
code:3 具体的重写特性类 目前我就重写了非空和正则表达式的特性 其他的可以自己扩展
namespace System.ComponentModel.DataAnnotations
{
public class MGRequiredAttribute : RequiredAttribute
{
private MyValidateHelper helper { get; set; }
public MGRequiredAttribute()
{
helper = new MyValidateHelper();
}
public string ValidateOperationType { get; set; }
public override bool IsValid(object value)
{
if (helper.IsContainsOperationType(ValidateOperationType))
{
if (value != null)
{
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
}
public class MGRegularExpression : RegularExpressionAttribute
{
private string patter { get; set; }
private MyValidateHelper helper { get; set; }
public MGRegularExpression(string pattern)
: base(pattern)
{
patter = pattern;
helper = new MyValidateHelper();
}
public string ValidateOperationType { get; set; }
public override bool IsValid(object value)
{
if (helper.IsContainsOperationType(ValidateOperationType))
{
if (value != null)
{
return Regex.IsMatch(value.ToString(), patter);
}
else
{
return true;
}
}
else
{
return true;
}
}
}
code:4 Model类如何加特性
///
/// 用户名
///
[DisplayName(“用户名”)]
[MGRequired(ErrorMessage = “用户名不能为空”, ValidateOperationType = “Add|Update”)]
public string Name { get; set; }
///
/// 密码
///
[DisplayName(“密码”)]
public string Pwd { get; set; }
///
/// 账号
///
[DisplayName(“账号”)]
[MGRequired(ErrorMessage = “账号不能为空”, ValidateOperationType = “Add|Update”)]
[MGRegularExpression(@"([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,5})+", ErrorMessage = “必须是邮箱类型”, ValidateOperationType = “Add|Update”)]
public string AccountNo { get; set; }
///
/// 年龄
///
[DisplayName(“年龄”)]
public string Age { get; set; }
///
/// 性别
///
[DisplayName(“性别”)]
public int Sex { get; set; }
Code:5 Action加特性
[ValidateOperationType("Add")]
public ActionResult Add(CLModel cl)
{
bool flag = ModelState.IsValid;
return Json(true);
}
[ValidateOperationType("Update")]
public ActionResult Update(CLModel cl)
{
bool flag = ModelState.IsValid;
return Json(true);
}