With a type-per-hierarchy approach to data mapping, one (or more) of the columns represents a classifier. In this scheme, the classifier field acts like metadata. This can also be a useful approach in ASP.NET MVC for designing a model which using CSS, needs to be displayed slightly differently depending on the value of a particular property.
In this example, I will be demonstrating a View that displays log enties, and which uses a different image depending on the severity levels.
Modeling the MetaData
This post assumes that you are using the built-in DataAnnotationsModelMetadataProvider or have created a custom ModelMetadataProvider that extends AssociatedMetadataProvider.
The simplest route is to just apply the ModelMetaData using the AdditionalMetadataAttribute to the Model:
1 2 3 4 5 | public class LogEntryModel { [AdditionalMetadata("Classifier", true)] public String Severity{ get; set; }<br><br> public DateTime EventDate{ get; set;}<br> public String Source {get; set;}<br> public String EventID {get; set;}<br> public String Category {get; set;}<br> public String Message{get; set;}<br>}<br><br> |
Customize the DisplayTemplate
Depending on where in your project you want this custom ModelMetadata to be applicable, you can scope the usage of this ModelMetada to the Views of a particular Controller, an Area, or Globally.
For our purposes, let’s assume that we want to apply the same behavior everywhere unless it is overridden. In that case you want to Create or Modify the Views/Shared/DisplayTemplates/String.cshtml template:
1 2 3 4 5 6 7 | @{ var isClassifier = (bool?)ModelMetadata<br> .FromLambdaExpression(x => x, ViewData).AdditionalValues["Classifier"];<br>}<br><br>@if (isClassifier.GetValueOrDefault())<br>{<br><span class='@ViewData.TemplateInfo.FormattedModelValue'><br> @ViewData.TemplateInfo.FormattedModelValue<br></span><br>}<br>else { @ViewData.TemplateInfo.FormattedModelValue } |