对ViewModel自定义约束
Posted Akeke
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了对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自定义约束的主要内容,如果未能解决你的问题,请参考以下文章
TextView 的自定义颜色与 Android Studio 显示的颜色不同
如何通过 viewModels 获取 viewModel? (片段-ktx)