DataAnnotations 属性是否被缓存?如果是这样,如何在不同文化之间进行切换?
我有一个支持美国和加拿大的网站。我的邮政编码验证使用我创建的自定义 RegEx 属性来允许本地化我的 RegEx 模式:
public class RegularExpressionAttribute : System.ComponentModel.DataAnnotations.RegularExpressionAttribute
{
public RegularExpressionAttribute(Type patternResourceType, string patternResourceName)
: this(ResourceHelper.GetString(patternResourceType, patternResourceName))
{
this.PatternResourceName = patternResourceName;
this.PatternResourceType = patternResourceType;
}
}
问题是,如果客户端从一个国家/地区切换到另一个国家/地区,它会保留第一个国家/地区的 RegEx 模式。因此,如果他们在美国加载,当他们切换到加拿大时,它会保留美国的邮政编码模式,反之亦然。
我怎样才能让它始终使用正确的文化?
提前致谢。
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.DataAnnotations.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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我找到了答案。创建自定义 DataAnnotationsModelMetadataProvider。这真的很容易。您只需要重写一个方法。每次需要属性时都会调用此函数。网上有很多这样的示例,例如: http://bradwilson.typepad.com/blog/2010/01/why-you-dont-need-modelmetadataattributes.html和 http://www.freewebdevelopersite .com/2011/07/10/custom-metadata-providers-in-asp-net-mvc/。
干杯
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