ASP.NET Core Razor Page中如何将资源文件键绑定到属性?
如何通过ComponentsResource.resx控制必填字段的错误信息
现有配置回顾
你已经实现了ComponentsResourceService并完成了本地化基础配置,接下来只需调整DataAnnotations的绑定方式,就能让必填字段的错误信息从ComponentsResource.resx中读取。
具体实现步骤
配置资源文件内容与位置
- 在
Resources文件夹下,按照ComponentsResource类的命名空间结构创建对应目录:Resources/NzShop/Services - 在该目录下添加对应文化的资源文件:
- 默认文化(英文):
ComponentsResource.resx,添加键值对:RequiredField→This field is required - 波斯语:
ComponentsResource.fa.resx,添加键值对:RequiredField→این فیلد الزامی است - 土耳其语:
ComponentsResource.tr.resx,添加键值对:RequiredField→Bu alan zorunludur
- 默认文化(英文):
注:资源文件命名必须与
ComponentsResource类完全一致,目录结构要匹配类的命名空间(NzShop.Services),确保本地化服务能正确定位资源。- 在
修改Program.cs中的DataAnnotations本地化配置
更新AddDataAnnotationsLocalization配置,指定使用ComponentsResource作为默认资源源:builder.Services.AddMvc() .AddViewLocalization() .AddDataAnnotationsLocalization(options => { options.DataAnnotationLocalizerProvider = (type, factory) => factory.Create(typeof(ComponentsResource)); });调整[Required]特性的属性
不再直接使用ErrorMessage,而是通过资源键和资源类绑定错误信息:using NzShop.Services; // 引入ComponentsResource所在的命名空间 [Required(ErrorMessageResourceName = "RequiredField", ErrorMessageResourceType = typeof(ComponentsResource))] public string Familly { get; set; }
额外说明
- 若要给不同字段设置专属提示,只需在资源文件中添加对应键(比如
Required_Familly),再在特性中指定该键即可。 - 系统会根据当前请求的文化,自动加载对应语言的错误信息。
内容的提问来源于stack exchange,提问作者Farna
相关产品推荐
相关产品推荐

