30

How would one get resx resource strings into javascript code stored in a .js file?

If your javascript is in a script block in the markup, you can use this syntax:

<%$Resources:Resource, FieldName %>

and it will parse the resource value in as it renders the page... Unfortunately, that will only be parsed if the javascript appears in the body of the page. In an external .js file referenced in a <script> tag, those server tags obviously never get parsed.

I don't want to have to write a ScriptService to return those resources or anything like that, since they don't change after the page is rendered so it's a waste to have something that active.

One possibility could be to write an ashx handler and point the <script> tags to that, but I'm still not sure how I would read in the .js files and parse any server tags like that before streaming the text to the client. Is there a line of code I can run that will do that task similarly to the ASP.NET parser?

Or does anyone have any other suggestions?

9 Answers 9

35

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.

Sign up to request clarification or add additional context in comments.

4 Comments

I use Framework 4, my app is Web, I have to add a reference to System.Windows.Forms.dll to resolve "ResXResourceReader" method. I can't make do enter to "ResourcesController", the ResourcesController class is in App_GlobalResources folder. I set the resx file as Build Action: Resource. I put a breakpoint and nothing.
The class to serialize to JSON is called JavaScriptSerializer, not Serializer and it's not static.
I am trying to use this, but I am never reaching in the controller. I have a break point in the action but it never reaches there. Plus <script src="/resources/Foo.js"></script> this going to be added in _layout.chtml file?
In addition to above answer, I had to add a handler to the web.config so that IIS wouldnt look for a static file at that address: <system.webServer> <handlers> <add name="ScriptsHandler" path="/resources/*.js" verb="GET" type="System.Web.Handlers.TransferRequestHandler" /> </handlers> </system.webServer>
21

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.

1 Comment

Hmm, an interesting approach. Might work for me. The drawbacks are that I have to have a separate resources file for only what I want to push out or else send extra stuff of no use... and that I'm inside sharepoint so reading the resx in as a file and parsing it may be a problem, we'll see. Thanks for the post!
6

whereas "Common" is the name of the resource file and Msg1 is the fieldname. This also works for culture changes.

            Partial Javascript...:
            messages: 
            {
                <%=txtRequiredField.UniqueID %>:{                       
                    required: "<%=Resources.Common.Msg1 %>",
                    maxlength: "Only 50 character allowed in required field."
                }
            }

1 Comment

Thanks! works perfect. code alert("<%=Resources.LocalizedText.ErrorMessage %>");
3

If you have your resources in a separate assembly you can use the ResourceSet instead of the filename. Building on @Domenics great answer:

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

    public ActionResult GetResourcesJavaScript()
    {
        // This avoids the file path dependency.
        ResourceSet resourceSet = MyResource.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);

        // Create dictionary.
        var resourceDictionary = resourceSet
                        .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.resources = {1};", json);

        return JavaScript(javaScript);
    }
}

The downside is that this will not enable more than one resource-file per action. In that way @Domenics answer is more generic and reusable.

You may also consider using OutputCache, since the resource won't change a lot between requests.

[OutputCache(Duration = 3600, Location = OutputCacheLocation.ServerAndClient)]
public ActionResult GetResourcesJavaScript()
{ 
    // Logic here...
}

http://www.asp.net/mvc/overview/older-versions-1/controllers-and-routing/improving-performance-with-output-caching-cs

3 Comments

In addition to above answer, I had to add a handler to web.config so that IIS wouldnt look for a static file at that address: <system.webServer> <handlers> <add name="ScriptsHandler" path="/resources/*.js" verb="GET" type="System.Web.Handlers.TransferRequestHandler" /> </handlers> </system.webServer>
@user1191559 that shouldn't be needed, since the answer I posted doesn't use the .js-suffix. It's just an endpoint as any else.
Hi @smoksnes, seeing that your answer didnt include the script implementation part, most users would be using Domenics implementation (that includes .js) so that case it should help!
2

In a nutshell, make ASP.NET serve javascript rather than HTML for a specific page. Cleanest if done as a custom IHttpHandler, but in a pinch a page will do, just remember to:

1) Clear out all the ASP.NET stuff and make it look like a JS file.

2) Set the content-type to "text/javascript" in the codebehind.

Once you have a script like this setup, you can then create a client-side copy of your resources that other client-side scripts can reference from your app.

Comments

0

I usually pass the resource string as a parameter to whatever javascript function I'm calling, that way I can continue to use the expression syntax in the HTML.

1 Comment

That would normally be my inclination as well, but in this case, it's a client side item clicked handler for a RadMenu, so it leads to a switch statement with 7 cases, all displaying different "are you sure?" strings :(
0

I the brown field application I'm working on we have an xslt that transforms the resx file into a javascript file as part of the build process. This works well since this is a web application. I'm not sure if the original question is a web application.

Comments

0

use a hidden field to hold the resource string value and then access the field value in javascript for example : " />

var todayString= $("input[name=TodayString][type=hidden]").val();

Comments

0

Add the function in the BasePage class:

    protected string GetLanguageText(string _key)
    {
        System.Resources.ResourceManager _resourceTemp = new System.Resources.ResourceManager("Resources.Language", System.Reflection.Assembly.Load("App_GlobalResources"));
        return _resourceTemp.GetString(_key);
    }

Javascript:

    var _resurceValue = "<%=GetLanguageText("UserName")%>";

or direct use:

    var _resurceValue = "<%= Resources.Language.UserName %>";

Note: The Language is my resouce name. Exam: Language.resx and Language.en-US.resx

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.