【问题标题】:ASP.NET 5: Is localization with DisplayAttribute gone?ASP.NET 5:DisplayAttribute 的本地化消失了吗?
【发布时间】:2015-10-20 16:28:31
【问题描述】:

我正在将应用程序从以前的 ASP.NET 版本迁移到 ASP.NET 5(vNext,MVC 6)。以前我本地化了带有DisplayAttribute 附加到 ViewModel 属性的表单:

[Required(ErrorMessageResourceName = "FieldIsRequired", ErrorMessageResourceType = typeof(Resources.Validation))]
[Display(Name = "UserName", ResourceType = typeof(Resources.Common))]
public string UserName { get; set; }

我添加了 DataAnnotations 服务:

public void ConfigureServices(IServiceCollection services)
{
    services.AddMvc()
            .AddViewLocalization(options => options.ResourcesPath = "Resources/Views")
            .AddDataAnnotationsLocalization();
}

当我提交无效表单时,错误消息会被本地化(在 [Required] 属性中指定)。

但是尝试显示表单时,我遇到了一个异常(资源类中没有公共属性“UserName”),直到我注释掉了[Display] 属性。

好像输入标签不能再用[DisplayAttribute] 本地化?

谢谢!

【问题讨论】:

  • 你有 resx 文件吗?你能把它也包括在你的帖子里吗?
  • 是的,.resx 文件是 asp.net 网站项目的一部分。我用它的内容(作为 xml)创建了一个粘贴:pastebin.com/7h1Vhu7s。生成的类确实有 internal 访问修饰符(我无法在 ASP.NET 5 项目中更改它),但它适用于验证错误消息。
  • 如果您手动将生成的类的修饰符更改为public,它应该可以工作。请留意此issue,它与您的问题有关。
  • 那么我们应该如何解决这个问题呢? stackoverflow.com/questions/37833661
  • @nativehr 你能举个例子说明你是如何使用 ErrorMessage-s 来实现这个功能的吗?

标签: localization data-annotations asp.net-core


【解决方案1】:

确实没了。根据documentation

运行时不会查找非验证属性的本地化字符串。在上面的代码中,“电子邮件”(来自 [Display(Name = "Email")])不会被本地化。

2017 年 3 月 20 日更新

根据updated documentation,新的 .NET Core SDK 重新启用了非验证属性的本地化:

DataAnnotations 错误消息已本地化为 IStringLocalizer<T>。 使用选项ResourcesPath = "Resources"RegisterViewModel 中的错误消息可以存储在以下任一路径中:

  • 资源/ViewModels.Account.RegisterViewModel.fr.resx
  • 资源/ViewModels/Account/RegisterViewModel.fr.resx

【讨论】:

    猜你喜欢
    • 2016-10-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-10-21
    • 1970-01-01
    • 1970-01-01
    • 2011-06-19
    • 1970-01-01
    相关资源
    最近更新 更多