Script resource localization in ASP.NET MVC

As modern web applications are becoming more and more reliant on JavaScript, and world of SPA is getting new members every day, I wanted to be able to localize JavaScript resources, so my dialogs and other JS-generated gui is localized.

As I’m doing development in ASP.NET, I already use resx files for my resources. And, with having my plan to localize SPA without reload, logical first step would be to be able to get localized resource values as JSON. So, I made simple ScriptsController and turned it into snippet for VS.

You can take this snippet, create ScriptsController.cs as empty mvc controller, and then use snippet inside your namespace to replace complete ScriptsController class. The only thing you need to replace is alias for Resource in using directives:

script controller

 

This works as it is for JSON request, but for standard request, you also need to add Resources.cshtml view, also available as snippet. This view basically creates a <script> tag with JS variable named Resources by default, which contains all items in it:

Resource.cshtml

 

How this looks like in practice?

JSON request:

json resource request

 

 

 

“Normal” request:

text resources requestresponse window - resource

 

 

 

 

 

 

 

 

 

In next post, I will use these resources to change localization language in Single Page App without reload.