1. 程式人生 > >對ViewModel自定義約束

對ViewModel自定義約束

reat ons turn lin amp equal 密碼 員工 listitem

有時候我們常要對一些屬性進行自定義的約束,可以這麽做

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自定義約束