Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Showing text from resources.resx in JavaScript

This is example code in ASP.NET MVC 3 Razor:

@section header
{
    <script type="text/javascript">    
        $(function() {
            alert('@Resources.ExampleCompany');
        });
    </script>
}

<div>
    <h1>@Resources.ExampleCompany</h1>
</div>

The code above this is just an example, but it also shows my problem with encoding. This variable @Resources.ExampleCompany is a file resources.resx with value ExampleCompany = "Twoja firma / Twój biznes"

In JavaScript, the alert shows the "Twoja firma / Tw&#243;j biznes".

Why is character 'ó' '&#243'? What am I doing wrong?

In HTML tag, <h1>@Resources.ExampleCompany</h1> is displayed correctly.

UPDATE:

Mark Schultheiss wrote a good hint and my "ugly solution" is:

var companySample = "@Resources.ExampleCompany";
$('#temp').append(companySample);
alert($('#temp').text());

Now the character is &#243; and looks good, but this is still not answer to my issue.

like image 991
stitch7c0 Avatar asked Feb 08 '12 09:02

stitch7c0


People also ask

How do you get a string from .resx file to a .JS file?

A quick method is that You can set the Javascript variable values in aspx file in advance. This will render the resource value in the alertMessage variable and you can use it wherever required. Add all the required resource variable to the resources_en to access them on client.


2 Answers

According to HTML Encoding Strings - ASP.NET Web Forms VS Razor View Engine, the @ syntax automatically HTML encodes and the solution is to use the Raw extension-method (e.g., @Html.Raw(Resources.ExampleCompany)) to decode the HTML. Try that and let us know if that works.

like image 162
pete Avatar answered Oct 12 '22 11:10

pete


Some of this depends upon WHAT you do with the text.

For example, using the tags:

<div id='result'>empty</div>

<div id='other'>other</div>

And code (since you are using jQuery):

var whatitis="Twoja firma / Tw&#243;j biznes";
var whatitisnow = unescape(whatitis);
alert(whatitis);
alert(whatitisnow);
$('#result').append(whatitis+" changed to:"+whatitisnow);
$('#other').text(whatitis+" changed to:"+whatitisnow);

In the browser, the "result" tag shows both correctly (as you desire) whereas the "other" shows it with the escaped character. And BOTH alerts show it with the escaped character.

See here for example: http://jsfiddle.net/MarkSchultheiss/uJtw3/.

like image 21
Mark Schultheiss Avatar answered Oct 12 '22 12:10

Mark Schultheiss