Friday, January 8, 2016

How to share Localization Resource in ASP.Net 5 MVC with Javascript

ASP.Net MVC projects can use Resource files to do localization. Its very easy to use those resource files in razor view files. For each resource, there are multiple resource files referring to different languages. ASP.Net treats those resource files as one resource class. The application will use specific language resource during the run time while one language is selected.

Regarding the Javascript, if we want to apply those resource files, we need to send them to Javascript one by one in razor file. To avoid those tedious process and to improve the independence of Javascript, we can create resource section in razor file using HTML 5 section tag. And let Javascript to read those resource by themselves. Here is the code in view:
<section class="myResouceLabels"
    data-Message1 = "@MyResources.MyMessage1"
    data-Message2 = "@MyResources.MyMessage2">
</section>
In your Javascript:
    // Return a message contained in the container
    function GetResourceMessage(msgId) {
        var container = $(".myResouceLabels");
        if (container.length == 0) return;
        return container.attr(msgId);
    }
    ....
    alert(GetResourceMessage(data-Message1);
    alert(GetResourceMessage(data-Message1);
Note section tag contained all attributes with data as leading string, which is different than other tags. Be careful not to make mistake!!!

Definitely, you need css decorating to let the section don't be displayed.
myResouceLabels { display: none }

No comments:

Post a Comment