2017-09-19 26 views
0

對不起,我的英語不太好,所以請儘量理解。爲什麼c#在剃鬚刀的js中解碼

下面是代碼:

@{ 
    Layout = null; 
    var str = "http://example.com?a=1&b=2"; 
} 

<html> 
    <head> 
     <meta name="viewport" content="width=device-width" /> 
     <title>Title</title> 
    </head> 
    <body> 
     <script> 
      $(function() { 
       console.log('@str'); 
      }); 
     </script> 
    </body> 
</html> 

我的期望是http://example.com?a=1&b=2,但在控制檯,結果是http://example.com?a=1&amp;b=2

請向我解釋,謝謝。

+0

我沒有看到任何不同嗎? – Se0ng11

+0

該字符串是否編碼?我沒有看到這些結果之間的任何區別。如果我的猜測正確,請使用'@ Html.Raw(str)'。 –

+0

@panshu您的期望和問題中的當前輸出是一樣的!隨着您發佈的代碼,當前輸出將是'http://example.com?a=1 & b = 2' – Shyju

回答

4

您所看到的編碼版本

http://example.com?a=1&amp;b=2 

因爲在剃刀,當您使用@前綴,剃鬚刀做HTML編碼渲染執行以下表達式的結果之前。因此,您所看到@改爲&amp;

如果你不希望這樣的事情發生,你可以用Html.Raw方法,它沒有做編碼

console.log('@Html.Raw(str)'); 

這將使

http://example.com?a=1&b=2 
+0

它的工作原理,謝謝shyju – panshu

0

如果您確定該網址不是由用戶輸入生成的,只能使用Html.Raw。此外,您可以使用Url.RouteUrl先生成網址。

@{ 
    string str = Url.RouteUrl("", new RouteValueDictionary(new { a = 9, b = 2}), "https", "example.com"); 
} 
<script src="~/Scripts/jquery-1.10.2.min.js"></script> 

<script> 
    $(function() { 
     console.log('@Html.Raw(str)'); 
    }); 
</script>