首页 > 代码库 > 对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自定义约束