What is the best way to retrieve a message from a resource file using JavaScript?

I have both English and Japanese resource files. When my website switches to Japanese language, I need the messages to display in Japanese just like they do in English. This will require dynamically displaying messages in JavaScript.

Thank you.

Answer №1

To easily incorporate resources.resx into your project, simply add the file to your project and implement the function outlined in the shared controller below:


#if !DEBUG
        [OutputCache(Duration = 24 * 60 * 60)]
#endif
        [AllowAnonymous]
        public ActionResult ResourcesForJavascript()
        {
            try
            {
                var resourceSet = JsResources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true);
                var resourceDictionary = resourceSet
                                .Cast<DictionaryEntry>()
                                .ToDictionary(entry => entry.Key.ToString(), entry => entry.Value.ToString());
                var json = JsonConvert.SerializeObject(resourceDictionary);
                var javaScript = $"window.Resources = window.Resources || {{}}; window.Resources.resources = {json};";
                return JavaScript(javaScript);
            }
            catch (Exception ex)
            {
                WebExceptionHelper.FillModelStateOrTempDataWithExceptionMessages(ex, ModelState, TempData);
                return null;
            }
        }

Then, include this script in the _Layout.cshtml as shown below:

<script type="text/javascript" src="@Url.Action("ResourcesForJavascript", "CommonActions")"></script>

Answer №2

When utilizing a resource file message, it is necessary to incorporate Localization into the corresponding view. For instance, if you have a view named abc.cshtml and wish to display an alert message from the resource file upon clicking a button:

View: abc.cshtml

@using Microsoft.AspNetCore.Mvc.Localization
@inject IViewLocalizer Localizer

In the script section:

<script type="text/javascript">
function executeOnClick(){
alert('@Localizer["Hello message from resource"]');
}
</script>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The functionality of clicking on a jQuery-generated element seems to be malfunctioning

When using Jquery, I am able to create an element and assign it the class .book: jQuery('<div/>', { name: "my name", class: 'book', text: 'Bookmark', }).appendTo('body'); I then wanted to add funct ...

The React JSON Unhandled Rejection problem requires immediate attention

While working on a form in React 16, I reached out to a tutor for some guidance. However, when trying to mock the componentDidMount, I encountered an error that has left me puzzled. The app still runs fine, but I am curious as to why this error is occurrin ...

Safari is struggling with the backface visibility feature not functioning as expected

I have implemented a cssflip animation in my code where the element rotates on hover. I included transition and backface-visibilty properties. While it works well on Chrome, I faced issues with Safari. I even added the webkit prefix for Safari browser. `. ...

Utilize Jquery's "find" function to showcase an image

I am attempting to showcase an image using jQuery. I have a function that accepts ID and PATH as parameters. The ID indicates the section (each section is an HTML page that loads upon user action). Additionally, there is a text area where I am displaying t ...

Having difficulty transmitting data from a view to an API controller

Hey there! I'm currently working on sending JSON data to the API controller through a HttpPost request to add that data to a file. This is what my JSON File looks like: { "students": [ { "Id": 1, "Name": "Ra ...

Invoke functions once the animation has finished

My current issue is as follows: I am trying to call two functions after an animation has completed. I have achieved calling one function using the provided example, but I need to call one more function as well. Here is the sample code: $('.content& ...

Issue with Mongoose schema: Unable to access the property 'password' as it is undefined

I recently attempted to implement passport local authentication based on a tutorial I found. Although everything appeared to be working correctly, I encountered an error when making a request using Postman: [nodemon] 1.18.11 [nodemon] to restart at any ti ...

Error: Async API Call Triggering Invalid Hook Invocation

When working with my functional component, I encountered an issue while trying to implement a react hook like useMemo or useEffect. It seems that the error may be caused by the asynchronous nature of the API call. In the service file: export const getData ...

Navigating the implementation of undefined returned data in useQuery hook within Apollo and ReactJS

I am facing an issue with my code where the cookieData is rendered as undefined on the initial render and query, causing the query to fail authentication. Is there a way to ensure that the query waits for the response from the cookie API before running? co ...

Can an IronPython asp.net webform be linked to a dll file?

With ASP.NET using the standard ASP model, it is possible to have the codefile of the aspx file in a dll by inheriting the class inside the dll. However, in IronPython there is a different model where the only option in the aspx page is "codefile" and th ...

The event is not triggered by ng-submit

I'm struggling with submitting this form. I've checked everything, but it just won't work. This is my HTML: <html ng-app = 'myApp'> <div ng-controller="Tabs"> ... <form ng-submit="sendClicked()" &g ...

Using AngularJS ui-router to implement Bootstrap UI tabs

Having trouble with Bootstrap UI Tabs in AngularJS ui-router. Trying to add an active class when refreshing the page. Passing the tab's URL to the asActive(url) function in my controller to compare with the current URL of the page. Using the "active" ...

In order to successfully utilize Node.js, Async.js, and Listeners, one must ensure

Here is the log output from the code below, I am unsure why it is throwing an error. It seems that the numbers at the end of each line represent line number:char number. I will highlight some important line numbers within the code. Having trouble with t ...

Endless waiting for C# asynchronous tasks

I am currently utilizing the power of "async" and "await" to download webpage content asynchronously, but I am facing a problem where the Tasks seem to be stuck indefinitely. Can you please help me identify the issue with the code snippet provided below? ...

Options for line colors in three.js

Here is the code I currently have: const materialLinearInterpolation = new THREE.LineBasicMaterial({ color: 0x0000c9, linewidth: 1 }) const pointsLinearInterpolation = [] for (var i = 0; i < this.pointsCoordinatesLinearInterpolation.length; i++) { ...

Issues with the Date Time Formatting in SQL Server

Recently, my ASP.NET application started encountering issues after I changed the datetime format in Regional and Language Settings within Control Panel. When I first installed XP, the date time format was set to default, but I later changed it to Indian s ...

Unable to set $_POST value when using $.ajax post request

I am a beginner in the world of PHP and JavaScript, and I have encountered an issue where I need to make changes to values in an XML document that has been read in. Specifically, I have an HTML Select element that was dynamically generated by PHP code. fu ...

How to insert an array into another array in JavaScript

Using Node, express, and mongoose to work on a project. I am attempting to include an Array as an element within another Array through a callback function. app.get('/view', function(req, res){ var csvRows = []; Invitation.find({}, func ...

There is no image to be found in the Next Js React project

My navbar component is displaying a logo perfectly in the development environment, as well as in the production build when viewed locally. However, once it is uploaded to Netlify, the image randomly goes missing. It's interesting to note that another ...

What could be causing the function to return undefined when using fetch, axios, ajax, or a promise?

When using asynchronous calls, the issue arises where the response is returned as undefined instead of the expected data. This problem can be seen in the following scenarios: Using Fetch const response = getDataWithFetch(); console.log(response); fun ...