Use ASP.NET Resource strings from within javascript files

Here is my solution for now. I am sure I will need to make it more versatile in the future... but so far this is good.

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" });

So I can do

<script src="/resources/Foo.js"></script>

and then my scripts can reference e.g. window.Resources.Foo.Bar and get a string.


There's no native support for this.

I built a JavaScriptResourceHandler a while ago that can serve Serverside resources into the client page via objects where each property on the object represents a localization resource id and its value. You can check this out and download it from this blog post:

http://www.west-wind.com/Weblog/posts/698097.aspx

I've been using this extensively in a number of apps and it works well. The main win on this is that you can localize your resources in one place (Resx or in my case a custom ResourceProvider using a database) rather than having to have multiple localization schemes.