asp.net-mvc - 在派生的 ViewModel 上覆盖 ValidationAttributes

标签 asp.net-mvc asp.net-mvc-2

我在 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 模型和逻辑来填充它。

最佳答案

这似乎是一个已知问题:
https://connect.microsoft.com/VisualStudio/feedback/details/483001/in-asp-net-mvc-generic-try-updatemodel-methods-ignore-subtype-properties

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/

相关文章:

c# - 为什么这个测试失败了?

c# - .NET显示不同的数据库变量但保存为ID?

asp.net-mvc - ASP.NET身份登录

asp.net-mvc - Asp.Net MVC - 所有 Controller 的通用数据

c# - 派生的RequiredAttribute不起作用

c# - 使用 MVC2 的 EditorFor helper 时如何控制 html 元素的 id 和名称

asp.net-mvc - 干净地更新 Entity Framework 中的层次结构

asp.net-mvc - MVC 3 RC 中的 Razor 助手

javascript - 在 .NET 应用程序中,是否有可能获得 Web 浏览器看到的 DOM 表示形式?

asp.net-mvc - 如何在 ASP.NET MVC 2 RC 中编写自定义客户端 jQuery 验证?