MVC2 DataAnnotations validation with inheritance

Posted by bhiku on Stack Overflow See other posts from Stack Overflow or by bhiku
Published on 2010-03-22T17:25:04Z Indexed on 2010/03/22 17:31 UTC
Read the original article Hit count: 700

Hi, 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 = "";
   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.

© Stack Overflow or respective owner

Related posts about asp.net-mvc2

Related posts about dataannotations