【问题标题】:Localizing ViewModel in ASP.NET MVC4 with Resources使用资源在 ASP.NET MVC4 中本地化 ViewModel
【发布时间】:2012-12-29 14:30:26
【问题描述】:

首先,我想澄清一下,我目前正在使用 ASP.NET MVC 的 Model 实体作为 ViewModel,因为我的项目是基于 MVCVM 的,所以我不会简单地混淆两者。

无论如何,MVC 会自动为我创建一些 ViewModel 实体的属性,如下所示(来自向导,已本地化为意大利语)

public class LoginModel
{
    [Required]
    [Display(Name = "Nome utente")]
    public string UserName { get; set; }

    [Required]
    [DataType(DataType.Password)]
    [Display(Name = "Password")]
    public string Password { get; set; }

    [Display(Name = "Memorizza account")]
    public bool RememberMe { get; set; }
}

将Display 属性替换为[Display(Name = LoginViewModelResources.lblUsername)] 会导致编译错误:“参数必须是常量表达式、typeof 表达式或矩阵创建表达式”。简而言之,属性引用是不行的。

Razor 视图使用如下标签来生成 HTML

@Html.LabelFor(m => m.UserName)
@Html.TextBoxFor(m => m.UserName)
@Html.ValidationMessageFor(m => m.UserName)

如何本地化 ViewModel 以便在前端显示正确的消息?

【问题讨论】:

标签: localization asp.net-mvc-4


【解决方案1】:

像这样:

[Required]
[Display(Name = "lblUsername", ResourceType = typeof(LoginViewModelResources))]
public string UserName { get; set; }

为此,您必须使用Custom Tool=PublicResXFileCodeGenerator 定义一个LoginViewModelResources.resx 文件(您在资源文件的属性中设置它)并包含一个标签lblUsername,它将保存本地化的资源。

【讨论】:

  • 我正要试试这个,但我相信LoginViewModelResources可以存储在单独的程序集中
  • 存储在哪里并不重要。重要的是您已经为其指定了PublicResXFileCodeGenerator 生成器,以便Visual Studio 生成一个public 的类包装器。默认情况下它使用 internal 修饰符,并且无法访问。
  • 如何动态切换资源文件?比如说你有法语和英语版本的资源文件,但是在显示中你已经硬编码了typof(XXX)....这意味着总是绑定到一个资源
  • @DanHunex,你可以通过更改当前的CultureInfo来切换。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2020-02-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-13
  • 2012-06-10
相关资源
最近更新 更多