本地化和DataAnnotations。 GlobalResourceProxyGenerator和PublicResxFileCodeGenerator

时间:2013-02-03 17:12:14

标签: c# asp.net-mvc localization

为什么DataAnnotation属性难以访问PublicResxFileCodeGenerator创建的资源?

我发现以下属性:

[Compare("NewPassword", ErrorMessageResourceName = "RegisterModel_ConfirmPasswordError", ErrorMessageResourceType = typeof(Resources.Global))]

如果使用PublicResxFileCodeGenerator创建资源,将无法找到该资源。但是,使用GlobalResourceProxyGenerator创建的相同资源将正常工作。两个资源文件都设置为Content,并存放在App_GlobalResources中。我已经尝试将默认语言放在App_LocalResources中,但它似乎没有任何区别。 我的测试是我的第二语言(GlobalResourceProxyGenerator)工作,但我的主要语言(PublicResxFileCodeGenerator)抛出异常(它无法找到资源文件)。如果我切换到GlobalResourceProxyGenerator,那么一切都很好(但显然没有公共访问)。

有谁知道这是为什么?我希望将来将资源转移到另一个程序集中。

1 个答案:

答案 0 :(得分:20)

那是因为您将资源文件放在App_GlobalResources文件夹中,该文件夹是ASP.NET中的特殊文件夹。如果您将资源文件放在其他位置,这应该有效。这也可能是与ASP.NET MVC应用程序完全独立的项目。

以下是您可以采取的步骤:

  1. 使用默认的互联网模板
  2. 创建新的ASP.NET MVC 3应用程序
  3. 添加包含~/Messages.resx资源字符串
  4. RegisterModel_ConfirmPasswordError文件
  5. 为此资源文件将自定义工具设置为PublicResXFileCodeGenerator

    enter image description here

  6. 添加模型:

    public class MyViewModel
    {
        [Compare("NewPassword", 
                 ErrorMessageResourceName = "RegisterModel_ConfirmPasswordError",
                 ErrorMessageResourceType = typeof(MvcApplication1.Messages))]
        public string Password { get; set; }
    
        public string NewPassword { get; set; }
    }
    
  7. 控制器:

    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            return View(new MyViewModel());
        }
    
        [HttpPost]
        public ActionResult Index(MyViewModel model)
        {
            return View(model);
        }
    }
    
  8. 查看:

    @model MyViewModel
    
    @using (Html.BeginForm())
    {
        <div>
            @Html.LabelFor(x => x.Password)
            @Html.EditorFor(x => x.Password)
            @Html.ValidationMessageFor(x => x.Password)
        </div>
    
        <div>
            @Html.LabelFor(x => x.NewPassword)
            @Html.EditorFor(x => x.NewPassword)
            @Html.ValidationMessageFor(x => x.NewPassword)
        </div>
    
        <button type="submit">OK</button>
    }
    
  9. 然后您可以通过提供相应的翻译开始本地化:

    • Messages.fr-FR.resx
    • Messages.de-DE.resx
    • Messages.it-IT.resx
    • Messages.es-ES.resx
    • ...

    更新:

    我在评论部分询问了App_GlobalResources文件夹有什么特别之处,以及为什么它不适合它。嗯,实际上你可以让它工作。您需要做的就是将Build Action设置为Embedded Resource。默认情况下,当您将文件添加到App_GlobalResources文件夹时,Visual Studio会将其设置为Content,这意味着此资源将不会合并到运行时程序集中,并且ASP.NET MVC无法找到它:

    enter image description here

相关问题