2015-06-22 101 views
0

我對ASP.NET MVC 4非常新,我試圖讓應用程序使用來自不同國家(Resource.en-us)的資源文件中的文本的.resx,Resource.es-Es.resx)如何從視圖和模型訪問資源(.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.但沒有別的可那裏,我不想讓每個視圖

+0

我認爲這個鏈接可以幫助你 的http:// stackoverflow.com/questions/6603050/how-to-access-my-resources-from-a-razor-view#6603050 –

+0

@AnkushJain我已經申請了,答案只提到如何從VIEW訪問它們而不是模型 –

+0

@MauricioGracia如何訪問視圖(CSHTML)和模型(CS)之間的資源沒有任何區別,那麼請您澄清一下爲什麼在CS中相同的代碼不適合你? –

回答

0

原來,你只需要這一行添加到任何模型

using Resources; //<<-- This line 

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

... 
} 
1

打開Resources.resx文件,在頂部有一個下拉選擇訪問修飾符,改變內部.resx文件公衆,你將能夠通過

Resources.STRING1 

訪問它們確保有命名空間一節中你的web.config

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

在您可以訪問resou模型類RCE中:

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

資源已經公開。我從一個EMPTY MVC4項目開始,可能缺少一些配置 –

0

Folloing this來看我添加了一個單獨的項目只是資源文件,並添加引用到Web應用程序項目。

然後,我會在我的dataannotations不僅使用,也適用於我的控制器和視圖不使用進口或使用的語句:

@section scripts { 
    <script type="text/javascript"> 

     $(function() { 
     $("#frm").data("CorregirError", "@Resources.CorregirError"); 
     }); 

    </script> 
} 
相關問題