【问题标题】:How can i create a common ViewModel with a varying Resource file?如何创建具有不同资源文件的通用 ViewModel?
【发布时间】:2012-03-01 06:02:36
【问题描述】:

我有一个这样的 ViewModel:

public class MyViewModel
{   
   [Display(Name = "One_Name", ResourceType = typeof(Resources.User.Resource1))]
   public string One { get; set; }

   [Display(Name = "Two_Name", ResourceType = typeof(Resources.User.Resource1))]
   public string Two { get; set; }
}

第 1 页上使用,当我做这样的事情时效果很好(例如拉回资源):

@Html.LabelFor(model => model.One)

但我也想在 第 2 页上使用此 ViewModel,但我不想将属性指向不同的资源文件(例如 Resources.User.Resource2)。

我不想欺骗班级,但我愿意接受一些 OO 技巧。

问题是属性参数必须是字符串、常量、typeof 或数组表达式。

解决这个问题的最佳方法是什么?

【问题讨论】:

  • 当我需要他时,@Darin Dimitrov 在哪里。 :)

标签: c# asp.net-mvc-3 razor internationalization resource-files


【解决方案1】:

是的,MVC 似乎不支持这种情况。您可以提供自己的 ResourceType 类,但它必须具有返回显示字符串的静态属性(例如您的示例中的 public static string One_Namepublic static string Two_Name),并且没有优雅的方法可以让它按照您的意愿行事。

但是由于Html.LabelFor 没有做任何特别惊天动地的事情,你可以很容易地在没有视图的情况下做到这一点。只需编写自己的<label> 元素并直接获取本地化字符串,就像调用ResourceManager.GetString 一样简单。在大多数情况下,您仍然可以使用Html.LabelFor,并且只在某些视图确实需要更改显示文本的情况下(希望很少见)使用编写自己的标签。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-30
    • 1970-01-01
    • 2021-01-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多