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?

1 Answer 1

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}.

Sign up to request clarification or add additional context in comments.

2 Comments

I suspected I would have to do this myself. Thanks
MyMessages should be MyResources right? it would have been perfect if it was passed as a type too

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.