Metadata and Metadata Attributes
This lesson explains how we can use property attributes to specify features that can be used each time a ViewModel is rendered.
We'll cover the following
We already used the DisplayAttribute
to specify the display name of properties and the DataTypeAttribute
to further constrain a property type, specifying if a DateTime
represents a date, a time, or a full DateTime, etc.
The above attributes are used by the ASP.NET Core framework itself to decide how to render ViewModel properties. There are also other attributes supported by ASP.NET Core we can use to define further property features. They are not used directly by ASP.NET Core default tag helpers, but they are available in our views so we can use them in our view code or also, in the definition of our custom tag helpers.
MetaData and MetaData providers
All metadata collected by the framework is available in all views through the ViewData.ModelExplorer
property. More specifically, ViewData.ModelExplorer.Metadata
contains all metadata associated with the view ViewModel. Metadata is useful for deciding how to render simple properties, so we should use ViewData.ModelExplorer.Metadata
only when the view ViewModel is a simple property.
When the view ViewModel is a complex type, we should use ViewData.ModelExplorer.GetExplorerForProperty(string name)
, instead. It returns all ModelExplorer
instances associated with each property of the ViewModel. The code below shows an example:
Get hands-on with 1400+ tech skills courses.