Search code examples
c#asp.net-mvclocalizationdisplayformat

Model Class DisplayFormat() How can I localization NullDisplayText?


public class Board
{
    [Display(ResourceType=(typeof(MVC.Resources.Board)), Name="TEST")]
    [DisplayFormat(NullDisplayText="")]
    public int? ItemId { get; set; }
    public string Title { get; set; }
    public string Contents { get; set; }
    public string Author { get; set; }
    public DateTime Date { get; set; }
}

this it MVC Model, How Can I DisplayFormat(NullDisplayText) localization


Solution

  • Here's what I did that works.

    I created the following class that could localize the NullDisplayText for any property.

    public class LocalizedNullDisplayText : DisplayFormatAttribute
    {
        private readonly PropertyInfo _propertyInfo;
    
        public LocalizedNullDisplayText(string resourceKey, Type resourceType)
            : base()
        {
            _propertyInfo = resourceType.GetProperty(resourceKey, BindingFlags.Static | BindingFlags.Public);
            if (_propertyInfo == null) return;
    
            base.NullDisplayText = (string)_propertyInfo.GetValue(_propertyInfo.DeclaringType, null);
        }
    }
    

    I referenced it like this:

    [LocalizedNullDisplayText("ReviewerName_NullTextDisplay", typeof(RestaurantReviewResources))]
    public string ReviewerName { get; set; }
    

    It works like a charm.