[英]Read value of another property in asp.net mvc2 custom attribute?
I have made custom attribute in my asp.net mvc2 project: 我在asp.net mvc2项目中设置了自定义属性:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)]
public class IsUsernameValidAttribute : ValidationAttribute
{
public override bool IsValid(object value)
{
if (value == null)
{
return true;
}
var username = value.ToString();
return UserBusiness.IsUsernameValid(username)
// && value of OtherProperty == true;
}
}
for the model: 对于模型:
public class MyClass
{
[IsUsernameValid]
public string UserName { get; set; }
public bool OtherProperty { get; set; }
}
I can get value of UserName, but can I get value of OtherProperty inside custom attribute and use it in return clause and how. 我可以获取UserName的值,但是可以在自定义属性中获取OtherProperty的值,并在return子句中以及如何使用它。 Thanks in advance.
提前致谢。
The only way to do this is with a class level attribute. 唯一的方法是使用类级别的属性。 This is often used for validating the
Password
and PasswordConfirmation
fields during registration. 这通常用于在注册期间验证
Password
和PasswordConfirmation
字段。
Grab some code from there as a starting point. 从那里获取一些代码作为起点。
[AttributeUsage(AttributeTargets.Class)]
public class MatchAttribute : ValidationAttribute
{
public override Boolean IsValid(Object value)
{
Type objectType = value.GetType();
PropertyInfo[] properties = objectType.GetProperties();
...
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.