I am trying to access the DataTypeName from the ModelMetadata in a custom DisplayTemplate, but it is always null. My goal is to make a decimal.cshtml template that looks for the DataTypeName and if it’s equal to Currency format it as currency. Otherwise display the decimal like normal.
Here’s an example of what I have now:
The Model:
public class MyModel
{
[DataType(DataType.Currency)]
public decimal foo { get; set; }
}
In a view that is strongly typed to MyModel I have a call like this: @Html.DisplayFor(m => m.foo)
The Display template (~/Views/Shared/DisplayTemplates/decimal.cshtml)
@model decimal?
@{
var type = ViewData.ModelMetadata.DataTypeName; // This is always null
}
I know that it’s using my DisplayTemplate like it’s supposed to, but I would expect the DataTypeName to not be null in this case since I have the DataType attribute on the model. Is there any way to access the DataType in a display template like this?
Strange, it should work. I am unable to reproduce. Here’s what I tried in a new application:
Model:
Controller:
View (
~/Views/Home/Index.cshtml):Display template (
~/Views/Home/DisplayTemplates/decimal.cshtml):When I run the application it prints
Currencyas expected.