【问题标题】:How to access Resources (.resx) text from View and Models如何从视图和模型访问资源 (.resx) 文本
【发布时间】:2015-06-22 16:21:11
【问题描述】:

我对 ASP.NET MVC 4 非常陌生,我正在尝试让一个应用程序使用来自不同国家的资源文件(Resource.en-us.resx、Resource.es-Es.resx)中的文本

我曾经有一个LocalResource 文件夹,我可以像这样从Model 访问它:

using Concordia_CRM.LocalResource;

[Required]
[Display(Name = "SD_NombreEmpresa", ResourceType = typeof(Resource))]
public string NombreEmpresa { get; set; }

但后来我也阅读了一些提到 App_LocalResources 的答案,我已经设法应用这些解决方案从 VIEW 访问文本,但现在不知道如何更改模型来访问它们。

我已阅读问题和答案:

How to use app_GlobalResource or app_LocalResource?

How does the App_LocalResources work with MVC?

但仍然没有找到一种方法来从视图和模型访问资源文件的文本,这种方法既紧凑又标准

从我尝试过的模型中

using Concordia_CRM.App_LocalResources <-- but this is not recognized

我可以输入Resources.Resource.,但那里没有其他可用的,我不想在每个视图中都有 .resx 文件

【问题讨论】:

  • 我觉得这个链接可以帮到你stackoverflow.com/questions/6603050/…
  • @AnkushJain 我已经应用了,答案只提到如何从视图而不是模型访问它们
  • @MauricioGracia 在视图 (CSHTML) 和模型 (CS) 之间访问资源的方式没有区别,所以请您解释一下为什么相同的代码在 CS 中不适合您?
  • @AlexeiLevenkov 我已经用我的具体问题更新了问题
  • 您是否必须使用本地/全局资源文件夹(因为您已经阅读了链接的答案,这在 MVC 中不是最简单的事情)?如果您已按照stackoverflow.com/questions/6603050/… 中概述的步骤进行操作,并且资源应该已生成并且对您的代码和视图可见...

标签: c# asp.net asp.net-mvc asp.net-mvc-4 localization


【解决方案1】:

打开 Resources.resx 文件,顶部有一个组合选择访问修饰符,更改为公共,您将可以通过以下方式访问它们

Resources.STRING1

确保您的 web.config 中有命名空间部分

<pages>
  <namespaces>
    <add namespace="ProjectName.App_LocalResources" />
  </namespaces>
</pages>

在模型类中你可以访问资源:

 public class model1
{
   [Required(ErrorMessage=App_LocalResources.Resource1.String1)]
    public string MyProp { get; set; }
}

【讨论】:

  • 资源已经公开。我从一个 EMPTY MVC4 项目开始,可能缺少一些配置
【解决方案2】:

原来你只需要将此行添加到任何模型中

using Resources;  //<<-- This line

namespace Concordia_CRM.Models
{
    public class SolicitudDemo
    {
        [Required]
        [Display(Name = "SD_NombreEmpresa", ResourceType = typeof(Resource))]
        public string NombreEmpresa { get; set; }

...
}

【讨论】:

    【解决方案3】:

    按照this 的观点,我为资源文件添加了一个单独的项目,并添加了对 Web 应用程序项目的引用。

    然后我将不仅在我的数据注释上使用,还可以在我的控制器和视图上使用,而不使用导入或使用语句:

    @section scripts {
       <script type="text/javascript">
    
          $(function () {
             $("#frm").data("CorregirError", "@Resources.CorregirError");
          });
    
       </script>
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-09
      • 2010-11-16
      • 2018-03-06
      • 1970-01-01
      • 1970-01-01
      • 2012-07-22
      • 1970-01-01
      • 2013-12-29
      相关资源
      最近更新 更多