Asp.Net MVC数据注释自定义属性不起作用

时间:2015-11-20 15:31:50

标签: c# asp.net-mvc validation asp.net-mvc-3 data-annotations

我需要实现一个cusotm属性,然后使用asp.net数据注释来验证一个类。不幸的是,在运行时不调用属性类。请帮帮我。非常感谢。以下是源代码。

using System;
using System.Collections.Generic;
using CaseMgr.Model.Base;

using System.Linq;
using System.ComponentModel.DataAnnotations;

namespace CaseMgr.Model.BusinessObjects
{
    public partial class PatLiverException : BusinessBase<decimal>, IComparable<PatLiverException>, IEquatable<PatLiverException>
    {
        private LiverExcepDisease _liverExcepDisease = null;
        private DateTime _sccApprovalDate = new DateTime();

        public PatLiverException() { }

        public virtual LiverExcepDisease LiverExcepDisease
        {
            get { return _liverExcepDisease; }
            set { _liverExcepDisease = value; }
        }

        [SccApprovalDateValidate("SccApprovalDate", "LiverExcepDisease")]
        public virtual DateTime SccApprovalDate
        {
            get { return _sccApprovalDate; }
            set { _sccApprovalDate = value; }
        }
    }

    public class SccApprovalDateValidateAttribute : ValidationAttribute
    {
        public string m_SccApprovalDate { get; private set; }
        public string m_LiverExcepDisease { get; private set; }

        public SccApprovalDateValidateAttribute(string SccApprovalDate_PropertyName, string LiverExcepDisease_PropertyName)
        {
            this.m_SccApprovalDate = SccApprovalDate_PropertyName;
            this.m_LiverExcepDisease = LiverExcepDisease_PropertyName;
        }

        protected override ValidationResult IsValid(object value, ValidationContext context)
        {
            var SccApprovalDate_Property = context.ObjectType.GetProperty(m_SccApprovalDate);
            DateTime SccApprovalDate_Value = (DateTime)SccApprovalDate_Property.GetValue(context.ObjectInstance, null);

            var LiverExcepDisease_Property = context.ObjectType.GetProperty(m_LiverExcepDisease);
            LiverExcepDisease LiverExcepDisease_Value = (LiverExcepDisease)LiverExcepDisease_Property.GetValue(context.ObjectInstance, null);

            if (SccApprovalDate_Value != null && SccApprovalDate_Value != DateTime.MinValue && SccApprovalDate_Value != DateTime.MaxValue)
            {
                return LiverExcepDisease_Value.Id == 10 ? ValidationResult.Success : new ValidationResult("When other, SccApprovalDate can not be null.");
            }
            else
            {
                return ValidationResult.Success;
            }
        }
    }
}

3 个答案:

答案 0 :(得分:0)

如果要在所需的类上使用验证属性:

System.in

https://msdn.microsoft.com/en-us/library/tw5zxet9.aspx?f=255&MSPPError=-2147217396

答案 1 :(得分:0)

看一下这篇文章:ASP.NET MVC: Custom Validation by DataAnnotation

另外,如果你在SccApprovalDateValidateAttribute.ValidationResult()中放入一个断点,它会被击中吗?

答案 2 :(得分:0)

您的代码看起来没问题,但我无法看到您调用的位置或使用属性SccApprovalDate,因为只有在运行时调用或使用该属性时才会调用在属性上声明的验证属性。你能发布如何使用SccApprovalDate属性吗?