简体   繁体   English

Razor在JavaScript中的撇号问题

[英]Apostrophe issue in JavaScript with Razor

It's simple! 这很简单!

This is my dynamic JavaScript code with Razor markup: 这是我的带有Razor标记的动态JavaScript代码:

<script type="text/javascript">
  $.fancybox.open(
    [
        @foreach (var class in GenericClass)
        {
            var aux = "{ href: 'http://localhost:63095" + Url.RouteUrl("Image") + "' }";
            <Text>@aux</text>
            break;
        }
    ],
    { helpers: { thumbs: { width: 75, height: 50 } }
  });    
</script>

This is what I get in any web browser: 这是我在任何网络浏览器中得到的:

<script type="text/javascript">
  $.fancybox.open(
    [
        { href: &#39;http://localhost:63095/Home/Image&#39; }
    ],
    { helpers: { thumbs: { width: 75, height: 50 } }
  });    
</script>

But this is what I really wanted to be generated: 但这是我真正想要生成的:

<script type="text/javascript">
  $.fancybox.open(
    [
        { href: 'http://localhost:63095/Home/Image' }
    ],
    { helpers: { thumbs: { width: 75, height: 50 } }
  });    
</script>

The problem is clear: instead of an apostrophe (') the output has &#39; 该问题是明显的:代替apostrophe (')的输出具有&#39; . Does someone know how I can generate the ' instead of &#39; 有人知道我如何生成'而不是&#39; ?

OBSERVATION : I already tried to do escaping and encoding but neither seems to work. 观察 :我已经尝试过转义和编码,但是似乎都没有用。

Maybe try including the value inline instead: 也许尝试改为包含值内联:

@foreach (var class in GenericClass)
{
  <Text>{ href: 'http://localhost:63095@(Url.RouteUrl("Image"))' }</text>
  break;
}

I believe that should fix the issue 我相信应该可以解决这个问题


Raw Html Approach 原始HTML方法

If you do need raw html you can use the following: 如果确实需要原始html,则可以使用以下代码:

@Html.Raw(myString)

Just be very careful with this especially if you are including values entered by the user since it could cause XSS or other security issues. 请特别注意这一点,特别是如果要包含用户输入的值,因为这可能会导致XSS或其他安全问题。

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

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