0

Is there a way to use the DisplayAttribute values of an entity within a view model?

public partial class Catalog
{
  [Display(ResourceType = typeof(Resources), Name = "ID")]
  public string ID { get; set; }

  [Display(ResourceType = typeof(Resources), Name = "CatalogName")]
  public string CatalogName { get; set; }
}

public class CatalogViewModel
{
  private readonly Catalog _catalog;

  // I want reuse Catalog.CatalogName's display values.
  public String CatalogName
  {
    get { return _catalog.CatalogName; }
  }
}

I cannot access Resources from the view model.

Display Name
  • 4,672
  • 1
  • 33
  • 43
Jordan
  • 9,642
  • 10
  • 71
  • 141

1 Answers1

0

Typically you wouldn't use domain objects within view models the way you do it here. The explanation why is it not a good practice (although functionally it will work) is here. What you would need to do is to define your view model from strings and ints (primitives) and use something like AutoMapper to map between them. In real life web site it is rare that you will have domain model mapped one to one to view model, typically view model is tailored for specific view carrying all the required information from multiple tables.

Back to your question: having view model defined according to best practices I just described, you certainly can (and should) define all annotations and validations (using fluent validation or data annotation)

Hope this helps, please let me know if not.

Community
  • 1
  • 1
Display Name
  • 4,672
  • 1
  • 33
  • 43