Are DataAnnotations attributes cached? If so, how to switch between different cultures?
I have a site that supports both US and Canada. My zip code validation uses a custom RegEx attribute that I created to allow my RegEx pattern to be localized:
public class RegularExpressionAttribute : System.ComponentModel.DataAnnotation开发者_运维技巧s.RegularExpressionAttribute
{
public RegularExpressionAttribute(Type patternResourceType, string patternResourceName)
: this(ResourceHelper.GetString(patternResourceType, patternResourceName))
{
this.PatternResourceName = patternResourceName;
this.PatternResourceType = patternResourceType;
}
}
The problem is, if the client switches from one country to the other, it holds onto the RegEx pattern from the first country. So if they load it in US, it keeps the US zip pattern when they switch to Canada, and vice versa.
How can I get this to always use the proper culture?
Thanks in advance.
I found the answer. Create a custom DataAnnotationsModelMetadataProvider. It's really easy. You just need to override a single method. This gets called every time a property attribute is required. There's quite a few samples on the web for this, eg: http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html and http://www.freewebdevelopersite.com/2011/07/10/custom-metadata-providers-in-asp-net-mvc/.
Cheers
精彩评论