在.js檔中用resx資源檔的方案

  • 1462
  • 0

摘要:在.js檔中用resx資源檔的方案

在webform中如果說要在Client端用 Resource檔 或許就是

  <%Resources.CommonRes.Error.ToString();%>

 

但.js檔中怎麼用呢?

 

建立一支ResourceHandler(JavaScriptResourceHandler.ashx)

然後用System.Resources 裡面的ResourceManage.GetResourceSet 讀取我們的.resx 來Cast Object建立 Dictionary物件 再用JSON格式把它Response 到快取裡 !!完成!!!!!!!!

.ashx

    public void ProcessRequest(HttpContext context)
    {
        var requestedCulture = new CultureInfo(context.Request.QueryString["locale"]);
        var classKey = context.Request.QueryString["classKey"];

        var dictionary = ReadResources(classKey, requestedCulture);

        var javaScriptSerializer = new JavaScriptSerializer();
        var script =
            @"
            if (typeof(Resources) == ""undefined"") Resources = {};
            Resources." + classKey + " = " +
            javaScriptSerializer.Serialize(dictionary) + ";";

        context.Response.ContentType = "application/javascript";
        context.Response.Cache.SetLastModified(DateTime.UtcNow);

        context.Response.Write(script);
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
    }

    private static Dictionary ReadResources(string classKey,
                                                       CultureInfo requestedCulture)
    {
        var resourceManager = new ResourceManager("Resources." + classKey,
                                            Assembly.Load("App_GlobalResources"));
        using (var resourceSet =
            resourceManager.GetResourceSet(CultureInfo.InvariantCulture, true, true))
        {

            return resourceSet
                .Cast()
                .ToDictionary(x => x.Key,
                     x => resourceManager.GetObject((string)x.Key, requestedCulture));
        }

    }

 

.aspx

 <!--------------------------註冊Resource檔------------------------->
    <script type="text/javascript" src="../ajax/JavaScriptResourceHandler.ashx?classKey=CommonRes&locale=<%=System.Globalization.CultureInfo.CurrentUICulture %>"></script>

 

使用方式

alert(Resources.CommonRes.UpdateError);

 

以上