0

I am trying to make my app international with multiple language support. I am using the resource file approach. So far so good, but is there a way to use the resource strings in my JS file?

Can I access them in JS file or it is not possible?

3
  • possible duplicate of How to use .net Resource files in javascript Commented Mar 10, 2015 at 13:37
  • I have seen that post but it doesn't gives an answer to what I need. The ajax solution proposed there would be like spamming the server. Commented Mar 10, 2015 at 13:41
  • Check this: stackoverflow.com/questions/940769/… and more in particular Domenic's answer. Hope this can help you! Commented Mar 10, 2015 at 13:47

2 Answers 2

0

The common approach to do localization in JavaScript is to override the fields by a localized JavaScript file which is loaded after the main one.

i.e your main app.js or whatever you call it declares an object:

DateTime = {}
DateTime.days = ["Sunday", "Monday", "Tuesday", ...];
DateTime.dateFormat = "m/d/Y";
DateTime.getToday = function(date) {
    var dayOfWeek = ...;
    return DateTime.days[dayofWeek];
}

Then in your localization file, let's call it locale_de-de.js you add

DateTime.days = ["Sonntag", "Montag", "Dienstag", ...];
DateTime.dateFormat = "d.m.Y";

That's also how most javascript frameworks (i.e. ExtJS, AngularJS) do their localizations. In your templates just do

@Scripts.Render("~/bundles/app")
@Scripts.Render("~/bundles/locale_de-de")

No need for resource strings and "parsing" your JavaScript files to replace the values with ones from Resource strings

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

Comments

0

Simplest way I have found is to create a javascript key-value pair in _Layout.cshtml using razor with resources:

var resourceData = { 'register_account_pesel_incorrect': '@LanguageResources.register_account_login_incorrect', 'register_account_password_incorrect': '@LanguageResources.register_account_password_incorrect' }

Then in your *.js file you simply use the resourceData like this:

options.messages["isLogin"] = resourceData['register_account_login_incorrect'];

Or even simplier:

options.messages["isLogin"] = resourceData.register_account_login_incorrect;

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.