Search code examples
asp.net-mvclocalizationactionfilterattributedisplayattribute

Localize DisplayNameAttributes in ActionFilter?


Is it possible to access the DisplayNameAttributes that are used on my ViewData.Model so I can Localize them before sending them to the view? Something like this:

Public Void OnActionExecuted(ActionExecutedContext: filterContext) {
  foreach (DisplayNameAttribute attr in filterContext...) {
    attr.TheValue = AppMessages.GetLocazation(attr.TheValue);
  }
}

What I'm missing is how to access the attributes. Is this possible at all?

P.S: We're using vb.net at my job and it's infiltrating my brain. So apologies if my C# is a tad off.


Solution

  • Don't change attribute values at runtime. In the best case this will be a no-op (as you'll be operating on copies of the attribute instances); in the worst case this will lead to race conditions in your code. Always treat attribute instances as immutable.

    If you need to localize [DisplayName], subclass it and override the virtual DisplayName property. See Localization of DisplayNameAttribute for an example of how to do this.