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?
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.
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."
}
}
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.
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
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.
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.
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();
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
How can i call javascript in a blazor server application? I am trying to follow this document
http://www.binaryintellect.net/articles/aede436b-4c57-4551-a7b4-a005f2aed499.aspx
On my ui.razor file i created the following code
#inject IJSRuntime JsRuntime;
...
private async void callWidgetApplication()
{
var fetched = await JSRuntime.InvokeAsync<bool>("fetchComponenent", DotNetObjectReference.Create(this));
}
I create a file on my wwwroot call Widget.js. this is what i have for the moment
function fetchComponenent() {
return true;
}
But i keep getting an error on my invokeasync.
CS1503 Argument 2: cannot convert from 'Microsoft.JSInterop.DotNetObjectReference<InfoAccessBlz.Pages.InfoAccess>' to 'object?[]?'
The whole reason in using javascript is to call an other website using ajax. So maybe if there is a better way, this is not an api, but its to retrieve an html site.
await JsRuntime.InvokeVoidAsync("fetchComponenent");
Your JavaScript Function doesn't accept any parameter and add the JavaScript file to the _Host.cshtml like this
<script src="~/Widget.js"></script>
I am trying to cache some results of a js script. (note this is working for other things like raw string data returned from a service, just not for this. Also note this is the first time I am trying to do it with a script and .js file.
Working:
in html:
<script src="https://www.notmydomain.com/script.js?param1=blah"></script>
not working:
in html:
<script src="/script.js?param1=blah"></script>
in #RestConroller method (from System.out.println's I know its returning the exact same thing as when I call the script directly):
#GetMapping("/script.js")
public String script(Model model, #RequestParam Map<String,String> allRequestParams) {
String parameters = inputParameterBuilder.buildParametersString(allRequestParams);
String js = pagesCacheService.getPage("script.js"+parameters, null, String.class);
if(null == js) {
js = resttemplate.getForObject("https://www.notmydomain.com/script.js" + parameters, String.class);
pagesCacheService.updatePage("script.js"+parameters, js, String.class);
}
return js;
}
Thanks,
Brian
Solved the issue: #GetMapping(value = "/script.js",produces = "text/javascript")
Heres my code but removed some changed code to something smaller!
Javascript code:
// /JS
function callme() {
var test = 1
alert(test);
}
Pug code:
// /first.pug
var funct = require('../JS');
button(onclick='clickme()') click
script.
function clickme() {ยจ
// trying to call callme function from my javascript file but i really dont know how.
callme();
}
Sorry about this question i dont use pug but this was already made with pug so i cannot go changing it since it has alot more code but didnt post all not needed code here.
Pug has no capability to directly run JavaScript. It is used to generate HTML.
You are already generating HTML with embedded client-side JavaScript.
You need to write the HTML to include the external JavaScript.
i.e. <script src="/url/to/JS.js"></script>
In Pug that would be:
script(src="/url/to/JS.js")
Make sure your HTTP server gives the JS a public URL!
My use case is that I have portions of js code that I would like to render based on some user permissions, with server side language being PHP.
Now I am currently using the Fat Free Framework, but even in other frameworks like laravel, I have only been able to find templates that template HTML.
I know I can use the templating engines that exist to just have conditional template logic to print a <script> tag given certain user permissions, but I haven't found any examples of how to do the following in a .js file
Example:
PHP:
$visible = ['section1' => true, 'section2' => true];
//this just renders the js file
render('test.js', ['visible' => $visible]);
test.js:
`//this is some kind of templating format`
{{if(isset($visible['section1']))}}
var a = 'Gin';
function sectionA(){
//do something
}
{{endif}}
{{if(isset($visible['section3']))}}
var b = 'Rum';
function sectionB(){
//do something
}
{{endif}}
The result would be that test.js would be rendered as
var a = 'Gin';
function sectionA(){
//do something
}
Alright, so after some playing around, I've figured out a solution. when building the html, you can echo a script that has a src of whatever resource you want. on the server side, respond to the javascript src route by rendering a js file (using the templating engine) that has the templating markups in it, and things will work as I wanted them to :)