1

I have a person class, which for the purpose of this question, is simply

public class Person
{
    [Required(ErrorMessage = "***")]
    [Display(Name = "Your full name")]
    public string Name { get; set; }
}

I inherit this is in my Complaints class

public class Complaints : Person
{
    [Required(ErrorMessage = "***")]
    [Display(Name = "Detail of the issue")]
    public string Detail{ get; set; }
}

Everything works as expected.

The problem is, we now want the user to not need to entire their name but, I have it already set to required.

Since my Person class is used else where, I can't change the Required attribute.

How can I override the DataAnnotations in my derived class? I'm guessing (which also explains my confusion) because the DataAnnotation belongs to the property that I can't just override the DataAnnocation and have to override the entire property?

MyDaftQuestions
  • 4,487
  • 17
  • 63
  • 120
  • 1
    Use the `new` keyword. Add a property to `Complaints` - `public new string Name { get; set; }` (without the attribute) or better, use view models. –  Jun 21 '15 at 09:24
  • Thank you. How do I use a ViewModel in this instance and how does it differ from a class with properties @StephenMuecke? – MyDaftQuestions Jun 21 '15 at 09:39
  • A view model is a class that is specific to a view. Refer [What is ViewModel in MVC?](http://stackoverflow.com/questions/11064316/what-is-viewmodel-in-mvc) –  Jun 21 '15 at 09:44

1 Answers1

0

You can use a custom DataAnnotationsModelMetadataProvider

public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
    protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
    {
        var modelMetadata = base.CreateMetadata(attributes, containerType, modelAccessor, modelType, propertyName);

        // fiddle with metadata here

        return modelMetadata;
    }
}

global_asax.cs

    protected void Application_Start()
    {
        ModelMetadataProviders.Current = new CustomModelMetadataProvider(); 

However, the real solution would be to separate your inheritance into a relationship. Think of things in 'real world' terms - like a dog is a animal, so: dog:animal and a dog has an owner so owner is a property of dog, dog doesn't inherit from owner. In this case, the person should be a property rather than the base case as a complaint is not a person.

freedomn-m
  • 27,664
  • 8
  • 35
  • 57