How to use resx file in javascript file. .net core 3.1 mvc
Asked Answered
D

2

5

I'am developing multi language web site with .net core mvc. I used Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer.

This code is work fine in .cshtml for me

@inject Microsoft.AspNetCore.Mvc.Localization.IHtmlLocalizer<ExampleProject.WEB.Controllers.HomeController> localizer

@localizer["NotificationManage"]

Also works between <script> tags in _Layout page

 alert('@localizer["NotificationManage"]');

But don't working in js file.

How to use Resx file in javascript file.?

What another best to way make multi language to javascript?

alert('@localizer["NotificationManage"]');

Not working for me.

Alert Result is:@localizer["NotificationManage"];

Demandant answered 26/1, 2021 at 9:56 Comment(1)
This answer will help https://mcmap.net/q/211059/-how-do-i-change-the-default-text-in-dropzone-jsMccall
A
10

One possible solution is to define your translations as a global variable on the window outside your script

<script>
var translations = {
   notification: '@localizer["NotificationManage"]'
}
</script>
<script type="text/javascript" src="pathtoscript.js"></script>

then inside your script you go

alert(window.translations.notification);

If any better solution is given here I'm happy to hear, because we use it this way in production

Airport answered 26/1, 2021 at 11:56 Comment(1)
since this is getting more upvotes then I could ever imagine I would strongly suggest you check out the blog post of the other answer, although my answer here is working it requires some coding, if you implement the blog post, resources will become automatically available to your js which is more desirable in some casesAirport
R
2

Another approach we could consider is to create a custom tag helper to convert the resource file contents to a global javascript object and then this variable object can be directly accessed in the external js files

It is mentioned in detail in this blog javascript localization worth a read.

Rounds answered 4/4, 2022 at 17:0 Comment(1)
This should be a comment under the question instead, not enough detail for an answerChristophany

© 2022 - 2024 — McMap. All rights reserved.