如何在JS文件中获取资源(.resx)字符串

时间:2016-05-17 04:41:50

标签: javascript c# asp.net-mvc model-view-controller multilingual

我正在multilingual中开发一个应用xyz.js,我的.js文件中有一些函数,但我不知道如何在{{1}}中获取资源字符串文件。我在网上已经探索了很多,但却找不到合适的答案。请帮我解决这个问题。

提前致谢。

2 个答案:

答案 0 :(得分:5)

没有原生支持在JavaScript中获取资源字符串,但我确信这会对您有所帮助。

v1 <- gsub("([^,]+),(\\s+[[:alpha:]]+)\\s*\\S*(\\s+[[:alpha:]]+\\s+\\d{4}-\\d{2}-\\d{2}.*)",
            "\\1\\2\\3", trimws(df1))
d1 <- read.table(text=v1, sep="", header=FALSE, stringsAsFactors=FALSE, 
 col.names = c("Num", "LastName", "FirstName", "Cat", "DOB", "Location"))
d1$Color <-  trimws(gsub("^[^,]+,\\s+[[:alpha:]]+|[[:alpha:]]+\\s+\\d{4}-\\d{2}-\\d{2}\\s+\\S+$",
                       "", trimws(df1)))
d1
#  Num   LastName FirstName Cat        DOB Location Color
#1  11    Jackson      Adam   L 1982-06-15      USA      
#2   2      Pearl       Sam   R 1986-11-04       UK      
#3   5 Livingston     Steph  LL 1983-12-12      USA      
#4   7   Thornton      Mark  LR 1982-03-26      USA      
#5  10     Silver      John  LL 1983-09-14      USA   RED

所以我可以做到

using System.Collections;
using System.Linq;
using System.Resources;
using System.Web.Mvc;
using System.Web.Script.Serialization;

public class ResourcesController : Controller
{
    private static readonly JavaScriptSerializer Serializer = new JavaScriptSerializer();

    public ActionResult GetResourcesJavaScript(string resxFileName)
    {
        var resourceDictionary = new ResXResourceReader(Server.MapPath("~/App_GlobalResources/" + resxFileName + ".resx"))
                            .Cast<DictionaryEntry>()
                            .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
        var json = Serializer.Serialize(resourceDictionary);
        var javaScript = string.Format("window.Resources = window.Resources || {{}}; window.Resources.{0} = {1};", resxFileName, json);

        return JavaScript(javaScript);
    }

}

// In the RegisterRoutes method in Global.asax:
routes.MapRoute("Resources", "resources/{resxFileName}.js", new { controller = "Resources", action = "GetResourcesJavaScript" });

然后我的脚本可以参考例如<script src="/resources/Foo.js"></script> 并获取字符串。

答案 1 :(得分:1)

我已经解决了这个问题。我在我的控制器中创建了一个方法,它将从资源文件中获取资源字符串,并在我的js文件中进一步使用该字符串。

  public JsonResult GetResourceString(string labelName)
    {
        string result ="";
        result = ResourceMessage.ResourceManager.GetString(labelName);
        if (Request.Cookies["culture"].Value == "th")
        {
            cul = CultureInfo.CreateSpecificCulture("th"); 
             result = ResourceMessage.ResourceManager.GetString(labelName,cul);
        }
        return Json(new
        {
            message = result
        }, JsonRequestBehavior.AllowGet);
    }

上面的方法将获取资源字符串,然后您可以使用它。 这里ResourceMessage是我的资源文件名,cul是CultuerInfo

谢谢:)