获取包含类,然后在自定义属性中访问它的属性
我正在使用 ASP.NET MVC 并通过模型上的自定义属性/数据注释实现自定义验证。
是否可以在我的自定义属性中访问对象父类的属性?
public class MyModel
{
[MyCustomValidator]
public string var1 {get; set;}
public string var2 {get; set;}
}
注意:使用 asp.net mvc
public class MyCustomValidatorAttribute : ValidationAttribute
{
public bool override IsValid(Object value)
{
// somehow get access to var2 in the MyModel
}
}
所以基本上,验证检查另一个属性的特定值。我尝试将 var2
的值作为参数传递给 MyCustomValidator
,但这不起作用。
I'm using ASP.NET MVC and implementing custom validation via custom attributes/data annotations on my models.
Is it possible to access a property on an object's parent class inside my custom attribute?
public class MyModel
{
[MyCustomValidator]
public string var1 {get; set;}
public string var2 {get; set;}
}
Note: Using asp.net mvc
public class MyCustomValidatorAttribute : ValidationAttribute
{
public bool override IsValid(Object value)
{
// somehow get access to var2 in the MyModel
}
}
So basically, making validation check another property for a specific value. I tried to pass var2
's value as a parameter to MyCustomValidator
but that doesn't work.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,基本上。通过反射器搜索后,您只能访问正在测试的成员的值 - 而不能访问包含对象,甚至不能访问属性/字段/其他内容的成员信息。
我同意这是非常有限和令人沮丧的,但看起来这在 4.0 中已修复 - 我之前的回复暗示对此,但在 4.0 中有一个
IsValid
接受ValidationContext
,它提供此信息通过对象实例
。No, basically. After a hunt through reflector, you only have access to the value of the member being tested - not the containing object or even the member-info of the property/field/whatever.
Which I agree is very limiting and frustrating, but it looks like this is fixed in 4.0 - my previous reply hinted at this, but in 4.0 there is an
IsValid
overload that accepts aValidationContext
, which provides this infomation viaObjectInstance
.显然,MVC 2 Validation 不支持
validationContext
,因为 MVC 2 的目标是 DA 3.5。我不确定 MVC 2 RC 是否仍然如此,我正在使用 VS 2010 和 MVC 2 Preview 1。摘自 Brad Wilson 的帖子 http://forums.asp.net/p/1457591/3650720.aspx
Apparently, MVC 2 Validation doesn't support
validationContext
because MVC 2 targets DA 3.5. I'm not sure if this is still the case with MVC 2 RC, I'm using VS 2010 with MVC 2 Preview 1.Taken from Brad Wilson's post at http://forums.asp.net/p/1457591/3650720.aspx
请注意,您可以使用 MVC3 执行此操作:
Just a note to say that you can do this with MVC3: