Asp.NetMVC数据注释自定义属性不起作用
本文关键字:自定义属性 不起作用 注释 数据 NetMVC Asp | 更新日期: 2023-09-27 18:22:50
我需要实现一个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;
}
}
}
}
如果要在需要的类上使用验证属性:
[AttributeUsage(AttributeTargets.Class)]
public class Sccxxxxxxxxx : ValidationAttribute
https://msdn.microsoft.com/en-us/library/tw5zxet9.aspx?f=255&MSPP错误=-2147217396
看看这篇文章:ASP.NET MVC:DataAnnotation 的自定义验证
此外,如果在SccApprovalDateValidateAttribute.ValidationResult()中放置断点,它会被命中吗?
您的代码看起来不错,只是我看不到您在哪里调用或使用属性SccApprovalDate,因为只有当运行时调用或使用该属性时,才会调用在该属性上声明的验证属性。你能发布你如何使用属性SccApprovalDate吗?