ASP.NET 5 MVC6 中数据模型注释的本地化和国际化

Localization and internationalization for data model annotations in ASP.NET 5 MVC6

我正在尝试将本地化与数据模型注释结合使用。

更新:添加示例代码并更改示例以反映代码

我准备了一个小的非工作示例,可以从这里克隆 https://bitbucket.org/feradz/dataannotationlocalization.git

加载页面浏览至http://localhost:6092/PersonalInfo/Edit

我有以下 class:

public class PersonalInfo 
{
    [Display(Name = "NameDisplay", ResourceType = typeof(PersonalInfo))]
    [Required(ErrorMessageResourceName = "NameRequired", ErrorMessageResourceType = typeof(PersonalInfo))]
    public string Name { get; set; }
}

我在目录 Resources.

中创建了 DataAnnotationLocalization.ViewModels.Member.PersonalInfo.resxDataAnnotationLocalization.ViewModels.Member.PersonalInfo.es.resx 资源文件

DataAnnotationLocalization.ViewModels.Member.PersonalInfo.resxDataAnnotationLocalization.ViewModels.Member.PersonalInfo.es.resx中我分别定义了NameDisplay=Name ENNameDisplay=Name ES

当我尝试加载页面时出现以下错误。

An unhandled exception occurred while processing the request.

InvalidOperationException: Cannot retrieve property 'Name' because localization failed. Type 'DataAnnotationLocalization.ViewModels.Member.PersonalInfo' is not public or does not contain a public static string property with the name 'resourceNameKey'.
System.ComponentModel.DataAnnotations.LocalizableString.<>c__DisplayClass12_0.<GetLocalizableValue>b__1()

在 ASP.NET 5 MVC6 中是否有开箱即用的支持?

它查找的资源是您的 class,而不是您的资源,因为资源和 class 同名:

public class <strong>PersonalInfo</strong>
{
    [Display(Name = "resourceNameKey", ResourceType = type(<strong>PersonalInfo</strong>))]
    public Title { get; set; }
}

您可以通过明确说明命名空间来解决此问题:

public class PersonalInfo
{
    [Display(Name = "resourceNameKey", ResourceType = type(<strong>Namespace1.Namespace2.</strong>PersonalInfo))]
    public Title { get; set; }
}

更新

要使您的示例有效:

namespace DataAnnotationLocalization.ViewModels.Member
{
    public class PersonalInfo
    {
        [Display(Name = "NameDisplay", ResourceType = typeof(<strong>DataAnnotationLocalization.Resources.DataAnnotationLocalization_ViewModels_Member_PersonalInfo</strong>))]
        [Required(ErrorMessageResourceName = "NameRequired", ErrorMessageResourceType = typeof(<strong>DataAnnotationLocalization.Resources.DataAnnotationLocalization_ViewModels_Member_PersonalInfo</strong>))]
        public string Name { get; set; }
    }
}

最好重命名资源文件,这样名称就不会与您在其中使用的 class 名称混淆。

问题出在资源class。

如果您使用 Visual studio 添加资源,它会为每个资源键生成带有内部 class 修饰符和内部属性修饰符的资源 class。

快速修复:您应该打开资源 class(与附加了 'Designer.cs' 的资源文件同名)并将 'internal' 更改为 'public'。并且每次将新密钥添加到资源文件时都必须这样做。这是 Visual Studio 2015 中的错误。