0

My viewmodel inherits from a class that inherits from an abstract class that has a property with a [Required] attribute, but the rule doesn't appear in the DOM and unobtrusive validation doesn't catch the error.

The display attribute goes through fine, but the validation DOM attributes are not added to the textarea

my view has this:

@model FormPersonView
....
@Html.TextAreaFor(m => m.Description)
@Html.ValidationMessageFor(m => m.Description)

my code has this:

public class FormPersonView : Person
{
    //View related stuff
    .....
    .....
}

public class Person : BasePerson
{
    //Person related stuff - validation for these work!
    [Required]
    public string FirstName { get; set; }
    [Required]
    public string LastName { get; set; }
}

public abstract class BasePerson
{
    //Base person stuff - validation for this doesn't work!
    public string Id { get; set; }

    [Required]
    [Display("Short description of the person")]
    public string Description { get; set; }
}

Why does it work with one level of inheritance but not two? It does work on the server side.

Madd0g
  • 3,841
  • 5
  • 37
  • 59

1 Answers1

1

Had exactly this problem. While defining the view, the model comes as a type you defined @model FormPersonView. Data annotations will only work on that specific type, even if you have derived properties from children, their data annotations won't be engaged.

The solution that I came up with in my project was to define editor templates for types I needed data annotations to work properly and then calling @EditorFor on those models. Then and only then were data annotations operating as expected.

Hope this help you.

Display Name
  • 4,672
  • 1
  • 33
  • 43
  • wow, I totally missed this answer, sorry. I still have this problem. I tried doing what you suggested (for the specific field only, not the entire form) and it still doesn't add the validation attributes to the HTML element. Going by my example, I tried having the model in the editor as both `BasePerson` and `FormPersonView`. – Madd0g Sep 08 '12 at 18:42
  • What I said was that if you have hieararchies of view models, you will have to define your decorations at leafs. In your case, regardless of what you define in `Person` or `PersonBase` - it won't show up as validation in the view. Define everything you need at `FormPersonView` level and accept it as a model type in your view - it must work by definition. Hope this clarifies my answer – Display Name Sep 09 '12 at 12:30