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?
A quick method is that You can set the Javascript variable values in aspx file in advance. This will render the resource value in the alertMessage variable and you can use it wherever required. Add all the required resource variable to the resources_en to access them on client.
Where to write JavaScript code in ASP.Net Form? You can write the JavaScript code in the ASP.Net Page in the following sections. You can write the JavaScript code in the head section, it is the recommended way to write the code, the code must be enclosed in the following syntax: <head id="Head1" runat="server">
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With