首页 > 代码库 > 对ViewModel自定义约束
对ViewModel自定义约束
有时候我们常要对一些属性进行自定义的约束,可以这么做
using ListSys.Entity; using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Web; using System.Web.Mvc; namespace ListSys.Models { public class UserViewModel { [Display(Name = "id")] public string Id { get; set; } [Required(ErrorMessage = "姓名必填")] [Display(Name = "姓名")] public string Name { get; set; } [CustomValidation(typeof(UserViewModel), "UnitAccout")] [Required(ErrorMessage = "账号必填")] [MinLength(length: 6, ErrorMessage = "账号长度不能小于6位")] [Display(Name = "账号")] public string Accout { get; set; } [Required(ErrorMessage = "密码必填")] [MinLength(length: 6, ErrorMessage = "密码长度不能小于6位")] [Display(Name = "密码")] public string Password { get; set; } [Required(ErrorMessage ="角色必填")] [Display(Name = "角色")] public string Role { get; set; } [Required] public string Type { get; set; } public IEnumerable<SelectListItem> GetRoles() { List<Role> roleList = new List<Role>(); roleList.Add(new Role() { RoleStr = "管理员", RoleVale = "admin" }); roleList.Add(new Models.Role() { RoleStr="员工",RoleVale="employee"}); return roleList.Select(a => new SelectListItem { Text = a.RoleStr, Value = a.RoleVale, }); } //验证账号是否是唯一的 public static ValidationResult UnitAccout(string value, ValidationContext pValidationContext) { string Accout = ((UserViewModel)pValidationContext.ObjectInstance).Accout; string Type= ((UserViewModel)pValidationContext.ObjectInstance).Type; using (var db=new zjtDBEntities()) { var userlist = db.User.Where(u => u.Accout == Accout).ToList(); if (userlist.Count>0 && Type.Equals("create")) { return new ValidationResult("该账号已注册"); } } return ValidationResult.Success; } } //角色类 public class Role { public string RoleStr { get; set; } public string RoleVale { get; set; } } }
对ViewModel自定义约束
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。