开发者

MVC2 DataAnnotations validation with inheritance

I have a .NET 2.0 class the properties of which are marked virtual.I need to use the class as a model in a MVC2 application. So, I have created a .NET 3.5 class inheriting from the .NET 2.0 class and added the DataAnnotations attributes to the overriden properties in the new class. A snippet of what I have done is below

// .NET 2.0 class
public class Customer
{
   private string _firstName = "";
  开发者_Go百科 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; }
   }
}

I have used the class as the model for a MVC2 view using the HtmlFor helpers. Serverside validation works correctly but the client side validation does not. Specifically the validation error is not displayed on the page.

What am I missing, or is it only possible to do this using buddy classes.

Thanks.

EDIT 1: I have now tried this with buddy validation classes and that doesn't work either.

EDIT 2: I have now worked out that the lambda expression supplied to the HtmlFor helpers is causing the problem. For e.g.

Html.TextBoxFor(m => m.FirstName) calls the ModelMetadata.FromLambdaExpression method which evaluates the DeclaringType of the MemberExpression (expression.Body) as the Customer class and not the MVCCustomer class.

I have tried changing the lambda expression to Html.TextBoxFor((MVCCustomer m) => m.FirstName) but the DeclaringType is still Customer.

Is there a way I can get the DeclaringType to be of type MVCCustomer and not Customer.


I have now got around this by using the new keyword on the properties in the .net 3.5 class as below

// .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; }
   }
}

This now works as expected and the DataAnnotations attributes from the MVCCustimer class are applied correctly.

Hope this helps


Silly question, but did you include the following scripts in your view/master file?

<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>

These are required for client side validation.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜