今天我写代码的时候,无意中有个需求需要在razor里写JS,当时各种写法都尝试了,还问过人,很多人都不知道正确的写法。
举个栗子:
如果我后台传过来一个值,在cshtml代码中根据这个值的类型去输出不同的JS
<pre name="code" class="csharp"> @if (ViewData["i"]!=1)
{
alert(ViewData["i"]);
}
else
{
alert("空");
}
这样的写法是有误的,无论是否在 alert(ViewData["i"]); 中的 ViewData["i"] 前加 @ 都是错误的。
因为 在 @if 的代码块里,已经从内容模式变为编译模式,编译器会默认 {} 里的代码全是 razor
通过使用<text>这个伪元素来强制Razor从编译模式返回到内容模式:
正确代码应该是这样:
<script type="text/javascript">
@if (ViewData["i"]!=null)
{
<text>
alert(ViewData["i"]);
</text>
}
else
{
<text>
alert("空");
</text>
}
</script>
这样razor 输出的结果会转为 text,最后作为JS脚本输出