Display Name
Display Name

Reputation: 4732

ASP.NET MVC ViewModels polymorphism

Folks, I have architectural question:

I have several viewmodels of very similar looking items, with different data annotations:

public class VM1 {
  [Display(Name="VM1 Field1")]
  public string Field1 { get; set; }
  [Display(Name="VM1 Field2")]
  public string Field2 { get; set; }
}
public class VM2 {
  [Display(Name="VM2 Field1")]
  public string Field1 { get; set; }
  [Display(Name="VM2 Field2")]
  public string Field2 { get; set; }
}
public class VM3 {
  [Display(Name="VM3 Field1")]
  public string Field1 { get; set; }
  [Display(Name="VM3 Field2")]
  public string Field2 { get; set; }
}

Is there a way for me to define one abstract class VMBase so that VM1/2/3 will inherit and how to assign the data annotation in that case? Basically class-wise its typical polymorphic situation, but data annotation - don't know how to handle those in this case?

Also how views needs to look so they will show proper class? Or will I have to multiply the entire thing 3 times (potentially the list will grow) just for data annotation sake?

If you think it can be done easier with fluent validation - please provide example (viewmodel, controller, view)

Edit But I am trying to stick with Data Annotations: those are for view models, while fluent validation is more for domain entities. I need client side validation that is coming from data annotation out of the box, and isn't from fluent validation.

Thank you in advance.

Upvotes: 1

Views: 506

Answers (1)

Chris Pratt
Chris Pratt

Reputation: 239290

I've had this same problem. However, I think I might have found a solution in FluentValidation. It's like the Fluent API for EF, if you've ever used that, but covers the validation facets that Fluent API doesn't, without having to resort to Data Annotations, which as you mention, makes it impossible to compose classes if the validation for a particular property will be different somewhere in the inheritance chain.

Upvotes: 1

Related Questions