Localize javascript messages and validation text

I’m working on a web project that is multilingual. For example, one portion of the project involves some custom google mapping that utilizes a client-side interace using jquery/.net to add points to a map and save them to the database.

There will be some validation and other informational messaging (ex. ‘Please add at least one point to the map’) that will have to be localized.

The only options I can think of right now are:

  1. Use a code render block in the javascript to pull in the localized message from a resource file
  2. Use hidden fields with meta:resourcekey to automatically grab the proper localized message from the resource file using the current culture, and get the .val() in jquery when necessary.
  3. Make a webservice call to get the correct message by key/language each time a message is required.

Any thoughts, experiences?

EDIT:

I’d prefer to use the .net resource files to keep things consistent with the rest of the application.

Answers:

Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.

Method 1

Ok, I built a generic web service to allow me to grab resources and return them in a dictionary (probably a better way to convert to the dictionary)…

<WebMethod()> _    
<ScriptMethod(ResponseFormat:=ResponseFormat.Json, UseHttpGet:=False, XmlSerializeString:=True)> _
    Public Function GetResources(ByVal resourceFileName As String, ByVal culture As String) As Dictionary(Of String, String)

        Dim reader As New System.Resources.ResXResourceReader(String.Format(Server.MapPath("/App_GlobalResources/{0}.{1}.resx"), resourceFileName, culture))
        If reader IsNot Nothing Then
            Dim d As New Dictionary(Of String, String)
            Dim enumerator As System.Collections.IDictionaryEnumerator = reader.GetEnumerator()
            While enumerator.MoveNext
                d.Add(enumerator.Key, enumerator.Value)
            End While
            Return d
        End If

        Return Nothing

    End Function

Then, I can grab this json result and assign it to a local variable:

// load resources
$.ajax({
    type: "POST",
    url: "mapping.asmx/GetResources",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: '{"resourceFileName":"common","culture":"en-CA"}',
    cache: true,
    async: false, 
    success: function(data) {
        localizations = data.d;                
    }
});

Then, you can grab your value from the local variable like so:

localizations.Key1

The only catch here is that if you want to assign the localizations to a global variable you have to run it async=false, otherwise you won’t have the translations available when you need them. I’m trying to use ‘get’ so I can cache the response, but it’s not working for me. See this question:

Can’t return Dictionary(Of String, String) via GET ajax web request, works with POST

Method 2

I’ve done this before where there are hidden fields that have their values set on Page_Init() and Page_Load() with the appropriate values from the global and local resource files. The javascript code would then work with those hidden values.

Code Behind

this.hfInvalidCheckDateMessage.Value = this.GetLocalResourceObject("DatesRequired").ToString();

Page.aspx

$('#<%= btnSearch.ClientID %>').click(function(e) {
    if (!RequiredFieldCheck()) {
        var message = $("#<%= hfInvalidCheckDateMessage.ClientID %>").val();
        alert(message);
        e.preventDefault();
        $("#<%= txtAuthDateFrom.ClientID %>").focus();
     }
 });

Disclaimer… Not sure if this was the best route or not, but it does seem to work well.

Method 3

I’ve implemented a modified version of the solution described here: http://madskristensen.net/post/Localize-text-in-JavaScript-files-in-ASPNET.aspx

I changed it to allow for multiple resource file names, if the need for it arises, by changing the regular expression and by using the HttpContext.GetGlobalResourceObject method to retrieve the resource string.

Method 4

I use this technique. It makes it easy for anyone with little coding experience to edit the phrase JavaScript file.

var lang = 0 // 0 = english, 1 = french
var phrases=[]

phrases["plans"] = "Rate Plans and Features|Forfaits et options").split("|")

then you output it as:

phrases["plans"][lang]

…add more columns as required.


All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

0 0 votes
Article Rating
Subscribe
Notify of
guest

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x