繁体   English   中英

在JavaScript中显示来自resources.resx的文本

[英]Showing text from resources.resx in JavaScript

这是ASP.NET MVC 3 Razor中的示例代码:

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

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

上面的代码只是一个例子,但它也显示了我的编码问题。 这个变量@ Resources.ExampleCompany是一个文件resources.resx ,其值为ExampleCompany = "Twoja firma / Twój biznes"

在JavaScript中,警报显示“ Twoja firma / Tw&#243;j biznes ”。

为什么角色'ó''&#243'? 我究竟做错了什么?

在HTML标记中,正确显示<h1>@Resources.ExampleCompany</h1>

更新:

Mark Schultheiss写了一个很好的提示,我的“丑陋的解决方案”是:

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

现在角色是&#243; 并且看起来不错,但这仍然不能解决我的问题。

根据HTML Encoding Strings - ASP.NET Web Forms VS Razor View Engine@语法自动进行HTML编码,解决方案是使用Raw扩展方法(例如, @Html.Raw(Resources.ExampleCompany) )来解码HTML 。 试试看,如果有效,请告诉我们。

我有类似的问题,但在我的情况下,我正在从Resource分配一个值到javascript变量。 字母ó编码存在同样的问题。 之后,这个变量被绑定到一个html对象(正好通过敲除绑定)。 在我的情况下,代码提供了一个技巧:

var label = '@Html.Raw(Resource.ResourceName)';

其中一些取决于您对文本的处理方式。

例如,使用标签:

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

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

和代码(因为你使用的是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);

在浏览器中,“result”标签正确显示(如您所愿),而“other”则显示转义字符。 并且两个警报都会显示转义字符。

请参见此处: http//jsfiddle.net/MarkSchultheiss/uJtw3/

我使用以下技巧:

<script type="text/javascript">
    $('<div/>').html("@Resources.ExampleCompany").text();
</script>

也许它会有所帮助。

UPDATE

我已经更彻底地测试了Razor的这种行为,我发现:

1.当文本作为html的正常内容放置时,@ Html.Raw方法只是帮助并写入没有html编码的char'ó'(不是:&#243;)

例:

<div> @Html.Raw("ó") </div>

例:

<script type="text/javascript">
    var a = $('<div/>').html('@("ó")').text();// or var a =  '@Html.Raw("ó")';
    console.log(a); // it shows: ó
</script>

但是如果将它作为属性放在html标签内,那么Razor会将其转换为:&#243; 和@ Html.Raw根本没有帮助

例:

<meta name="description" content="@("ó")" />

Yo可以通过将整个标记放到Resource(如该帖子中)或字符串(如我的示例中)来修复它

@("<meta name="description" content="ó" />")

所以,有时候有些人可能会对答案帮助其他人而不是他而感到困惑。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM