简体   繁体   English

ASP.NET MVC-显示单引号时剃须刀上的错误

[英]ASP.NET MVC - bug on razor when displaying single quote

I just noticed when I do something like this: 我只是注意到当我做这样的事情时:

@{
    String var1 = "there's error to this string";
}

<script>
    alert('@var1');
</script>

when I start running this and I look at alert box, the single quote character is transforming into weird display starting with #. 当我开始运行此命令并查看警报框时,单引号字符将转换为以#开头的怪异显示。

but when I just directly placing the string value to alert box, it works as expected: 但是当我直接将字符串值放置到警报框中时,它可以按预期工作:

<script>
    alert("there's error to this string");
</script>

I hope somebody could explain here why it happens. 我希望有人可以在这里解释为什么会发生。

您需要对字符串进行Javascript编码,然后告诉Razor不要对其进行HTML编码:

@Html.Raw(HttpUtility.JavaScriptStringEncode(var1))

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

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