Qui*_*ome 23 c# asp.net-mvc localization
为什么DataAnnotation属性难以访问PublicResxFileCodeGenerator创建的资源?
我发现以下属性:
[Compare("NewPassword", ErrorMessageResourceName = "RegisterModel_ConfirmPasswordError", ErrorMessageResourceType = typeof(Resources.Global))]
Run Code Online (Sandbox Code Playgroud)
如果已使用PublicResxFileCodeGenerator创建资源,将无法找到该资源.但是,使用GlobalResourceProxyGenerator创建的相同资源将正常工作.两个资源文件都设置为Content,并存放在App_GlobalResources中.我已经尝试将默认语言放在App_LocalResources中,但它似乎没有任何区别.我的测试是我的第二语言(GlobalResourceProxyGenerator)工作,但我的主要语言(PublicResxFileCodeGenerator)抛出异常(它无法找到资源文件).如果我切换到GlobalResourceProxyGenerator然后一切都很好(但显然没有公共访问).
有人知道为什么吗?我想将来将资源转移到另一个程序集中.
Dar*_*rov 20
那是因为您将资源文件放在App_GlobalResources
ASP.NET中的特殊文件夹文件夹中.如果您将资源文件放在其他位置,这应该有效.这也可能是与ASP.NET MVC应用程序完全独立的项目.
以下是您可以执行此操作的步骤:
~/Messages.resx
包含RegisterModel_ConfirmPasswordError
资源字符串的文件将自定义工具设置PublicResXFileCodeGenerator
为此资源文件:
添加模型:
public class MyViewModel
{
[Compare("NewPassword",
ErrorMessageResourceName = "RegisterModel_ConfirmPasswordError",
ErrorMessageResourceType = typeof(MvcApplication1.Messages))]
public string Password { get; set; }
public string NewPassword { get; set; }
}
Run Code Online (Sandbox Code Playgroud)控制器:
public class HomeController : Controller
{
public ActionResult Index()
{
return View(new MyViewModel());
}
[HttpPost]
public ActionResult Index(MyViewModel model)
{
return View(model);
}
}
Run Code Online (Sandbox Code Playgroud)视图:
@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>
}
Run Code Online (Sandbox Code Playgroud)然后,您可以通过提供相应的翻译开始本地化:
更新:
在评论部分我被问到这个App_GlobalResources
文件夹有什么特别之处,以及它为什么不能用它.嗯,实际上你可以让它工作.您需要做的就是设置Build Action
为Embedded Resource
.默认情况下,当您将文件添加到文件App_GlobalResources
夹时,Visual Studio将其设置为Content
意味着此资源不会合并到运行时程序集中,并且ASP.NET MVC无法找到它: