I'd like to format my model data using the DisplayFormat data annotation, but I want to use the format string stored in resource file. I have been able to pass the resource type and name to some data annotations such as when specifying error messages. How do I tell DisplayFormat to get the format string from one of my resource files?
Asked
Active
Viewed 2,216 times
1 Answers
8
The standard DisplayFormat
attribute doesn't allow you to do that. You could write a custom attribute to achieve this functionality:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = false)]
public class LocalizedDisplayFormatAttribute : Attribute, IMetadataAware
{
public string DataFormatStringResourceName { get; set; }
public bool ApplyFormatInEditMode { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
if (!string.IsNullOrEmpty(DataFormatStringResourceName))
{
if (ApplyFormatInEditMode)
{
metadata.EditFormatString = MyMessages.ResourceManager.GetString(DataFormatStringResourceName);
}
metadata.DisplayFormatString = MyMessages.ResourceManager.GetString(DataFormatStringResourceName);
}
}
}
and then:
public class MyViewModel
{
[LocalizedDisplayFormat(DataFormatStringResourceName = "DobFormat", ApplyFormatInEditMode = true)]
public DateTime Dob { get; set; }
}
and inside MyResources.resx
you could have a DobFormat
string value: {0:dd-MM-yyyy}
.

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
I suspected I would have to do this myself. Thanks – Matt Esch Feb 22 '12 at 11:13
-
`MyMessages` should be `MyResources` right? it would have been perfect if it was passed as a type too – CME64 Oct 17 '16 at 08:25