我在 MVC2 应用程序中有一个实例,其中两个 View 之间的唯一区别是对同一字段的范围验证检查略有不同。为了使应用程序尽可能干燥,我想知道是否可以以某种方式覆盖验证属性。
我试图有一个派生的 ViewModel 覆盖该属性并以不同的方式实现范围检查,如下所示:
public class Base
{
[Range(1, 100)]
public virtual int SomeProperty { get; set; }
}
public class Derived : Base
{
[Range(2, 100)]
public override int SomeProperty { get; set; }
}
但是,当我尝试 MVC 客户端验证似乎仍然继续获取基类的验证属性而不是派生属性时。
我知道有一种想法说我应该有一个完全不同的 ViewModel 并且永远不要继承,但它只是感觉很不对。我会复制 View 、 View 模型和逻辑来填充它。
最佳答案
Thank you for reporting this issue. This is a deliberate design decision with the model binding feature of ASP.NET MVC. To override the type that gets used you can specify an explicit type when you call UpdateModel and TryUpdateModel: UpdateModel(model); When you leave out the type the compiler will use its type inference logic to guess the type that you meant. In this case it makes a guess that is incorrect.
(未经自己测试)我建议在绑定(bind)期间尝试将类型转换为子类型,看看这是否会强制它识别属性。
关于asp.net-mvc - 在派生的 ViewModel 上覆盖 ValidationAttributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7961983/