2009-06-15 36 views
1

在我的ASP.NET MVC應用程序中,我管理位於App_GlobalResources文件夾中的.resx文件中的本地化文本。我可以在任何知道其密鑰的文件中檢索任何文本值。如何檢索位於App_GlobalResources中的資源文件中的所有鍵值對

現在,我想檢索特定資源文件中的所有鍵/值對,以便將結果寫入某個JavaScript。搜索顯示我可能能夠使用ResXResourceReader類並遍歷這些對;但不幸的是,該課程位於System.Windows.Forms.dll,我不想將該依賴關係連接到我的Web應用程序。有沒有其他方法可以實現此功能?

回答

2

我找到了解決方案。現在不需要引用Forms.dll。

public class ScriptController : BaseController 
{ 
    private static readonly ResourceSet ResourceSet = 
     Resources.Controllers.Script.ResourceManager.GetResourceSet(CurrentCulture, true, true); 

    public ActionResult GetResources() 
    { 
     var builder = new StringBuilder(); 
     builder.Append("var LocalizedStrings = {"); 
     foreach (DictionaryEntry entry in ResourceSet) 
     { 
      builder.AppendFormat("{0}: \"{1}\",", entry.Key, entry.Value); 
     } 
     builder.Append("};"); 
     Response.ContentType = "application/x-javascript"; 
     Response.ContentEncoding = Encoding.UTF8; 
     return Content(builder.ToString()); 
    } 
} 
+0

優秀的男人!!!!!!!!!!!!!! – 2009-07-04 13:53:02

0

好的,沒有其他答案。看起來像引用Forms.dll是目前唯一的方法。這是我想出的代碼。

public class ScriptController : BaseController 
{ 
    private const string ResxPathTemplate = "~/App_GlobalResources/script{0}.resx"; 
    public ActionResult GetResources() 
    { 
     var resxPath = Server.MapPath(string.Format(ResxPathTemplate, string.Empty)); 
     var resxPathLocalized = Server.MapPath(string.Format(ResxPathTemplate, 
      "." + CurrentCulture)); 
     var pathToUse = System.IO.File.Exists(resxPathLocalized) 
          ? resxPathLocalized 
          : resxPath; 

     var builder = new StringBuilder(); 
     using (var rsxr = new ResXResourceReader(pathToUse)) 
     { 
      builder.Append("var resources = {"); 
      foreach (DictionaryEntry entry in rsxr) 
      { 
       builder.AppendFormat("{0}: \"{1}\",", entry.Key, entry.Value); 
      } 
      builder.Append("};"); 
     } 
     Response.ContentType = "application/x-javascript"; 
     Response.ContentEncoding = Encoding.UTF8; 
     return Content(builder.ToString()); 
    } 
} 
相關問題