3
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

tereško
  • 58,060
  • 25
  • 98
  • 150
user3444535
  • 233
  • 1
  • 2
  • 12
  • 1
    I have edited your title. Please see, "[Should questions include “tags” in their titles?](http://meta.stackexchange.com/questions/19190/)", where the consensus is "no, they should not". – John Saunders Aug 26 '14 at 02:34

2 Answers2

4

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.

  • 1
    But It's only working once. Once you load the page and then change the culture and reload the page it's not working. it's shows the old resource value. – Justin CI May 19 '15 at 13:21
  • I believe this is due to caching. I think the culture selection is automatically cached. That's my guess without pulling up my test code and researching. In practice, though, users won't be changing their culture in that fashion. Their browser will be set to the same culture throughout the use of your application. – Jerry Benson-Montgomery May 21 '15 at 20:33
  • @JerryBenson-Montgomery the constructor of you Attribute will only be called once per app domain, so no the text will not change based on the Culture it will stay there until a new app domain is created.. – Peter Apr 21 '16 at 06:48
0
    public class LocalizedDisplayFormatAttribute : DisplayFormatAttribute
{
    public LocalizedDisplayFormatAttribute()
        : base()
    {
    }

    public new string NullDisplayText
    {
        get
        {
            return base.NullDisplayText;
        }
        set
        {
            base.NullDisplayText = /* Return Text */;
        }
    }
}
user3444535
  • 233
  • 1
  • 2
  • 12