3

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?

Matt Esch
  • 22,661
  • 8
  • 53
  • 51

1 Answers1

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