Using resource files (.resx) in javascript

10,004

Solution 1

I had a similar situation and in my case, I created a separate partial view which only contained a javascript block where I put all the resource strings required for use in client side logic. Every resource string was defined as a javascript variable. You could also create an associative array.

In your partial view:

var Resources = {
        January : "@Html.Raw(ISt_Localization.January)",
        February : "@Html.Raw(ISt_Localization.February)",
        ...
};

Solution 2

You can also try the below thing directly

@using Resources

<script>
var value = '@Resource.January';
/* work with value 
.......
.....

*/
</script>
Share:
10,004
Utarehpson
Author by

Utarehpson

internship

Updated on June 13, 2022

Comments

  • Utarehpson
    Utarehpson almost 2 years

    I'm trying to use localization in my project but I can't find a way to access my resx files from javascript. I have been looking around a bit and I don't think the 'AJAX call' method would be ideal for my project since I have quiet a lot of string that need to be fetched and it would just have to spam the server hard!

    if I just put it in my HTML then it works with this code:

    @using Resources
    <p>@Html.Raw(ISt_Localization.January)</p>
    

    I guess one of the things I could do is put all the strings in a hidden div and then get the content from the divs in my javascript but this wouldn't be very effective..

  • Utarehpson
    Utarehpson about 11 years
    Works like a charm! created a partial view. and make a list like in your example. Then used the items where I needed them! wish I could double vote this up!