【问题标题】:MVC2 DataAnnotations validation with inheritanceMVC2 DataAnnotations 验证与继承
【发布时间】:2010-03-22 17:25:04
【问题描述】:

我有一个 .NET 2.0 类,其属性标记为虚拟。我需要将该类用作 MVC2 应用程序中的模型。因此,我创建了一个继承自 .NET 2.0 类的 .NET 3.5 类,并将 DataAnnotations 属性添加到新类中被覆盖的属性中。下面是我所做的一个sn-p

// .NET 2.0 class
public class Customer
{
   private string _firstName = "";
   public virtual string FirstName
   {
      get { return _firstName; }
      set { _firstName = value; }
   }
}

// .NET 3.5 class
public class MVCCustomer : Customer
{
   [Required(ErrorMessage="Firstname is required")]
   public override string FirstName
   {
      get { return base.FirstName; }
      set { base.FirstName = value; }
   }
}

我使用 HtmlFor 帮助器将该类用作 MVC2 视图的模型。服务器端验证正常工作,但客户端验证不能。具体来说,验证错误不会显示在页面上。

我错过了什么,或者只能使用伙伴课程来做到这一点。

谢谢。

编辑 1: 我现在已经用伙伴验证类尝试了这个,但这也不起作用。

编辑 2: 我现在已经发现提供给 HtmlFor 助手的 lambda 表达式导致了问题。例如

Html.TextBoxFor(m => m.FirstName) 调用 ModelMetadata.FromLambdaExpression 方法,该方法将 MemberExpression (expression.Body) 的 DeclaringType 评估为 Customer 类,而不是 MVCCustomer 类。

我尝试将 lambda 表达式更改为 Html.TextBoxFor((MVCCustomer m) => m.FirstName) 但 DeclaringType 仍然是 Customer。

有没有办法让 DeclaringType 的类型为 MVCCustomer 而不是 Customer。

【问题讨论】:

  • 你调用 EnableClientValidation 了吗?
  • 是的,从aspx页面调用EnableClientValidation。

标签: asp.net asp.net-mvc-2 data-annotations


【解决方案1】:

我现在已经通过在 .net 3.5 类中的属性上使用 new 关键字来解决这个问题,如下所示

// .NET 2.0 class
public class Customer { 
  private string _firstName = "";
  public string FirstName
  {
     get { return _firstName; }
     set { _firstName = value; }
  }
}

// .NET 3.5 class
public class MVCCustomer : Customer {
   [Required(ErrorMessage="Firstname is required")]
   public new string FirstName 
   { 
      get { return base.FirstName; } 
      set { base.FirstName = value; }
   }
}

现在可以按预期工作,并且正确应用了 MVCCustimer 类的 DataAnnotations 属性。

希望对你有帮助

【讨论】:

    【解决方案2】:

    愚蠢的问题,但您是否在视图/主文件中包含以下脚本?

    <script src="../../Scripts/MicrosoftAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcAjax.js" type="text/javascript"></script>
    <script src="../../Scripts/MicrosoftMvcValidation.js" type="text/javascript"></script>
    

    这些是客户端验证所必需的。

    【讨论】:

    • 是的,我已将脚本添加到母版页。为了解决这个问题,我创建了镜像 .NET 2 类的 .NET 3.5 类,将 DataAnnotations 应用于 .NET 3.5 类,并使用反射将属性复制到 .NET 2 类。不理想,但它有效。我很惊讶,因为我预计这会开箱即用。
    猜你喜欢
    • 1970-01-01
    • 2013-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-31
    • 1970-01-01
    • 1970-01-01
    • 2011-02-18
    相关资源
    最近更新 更多