在JavaScript条件陈述中使用Razor语法

Dav*_*gel 2 javascript c# asp.net-mvc conditional razor

在index.cshtml中,我有以下类似的工作代码:

<script type="text/javascript">

if ('@Model.SomeCondition' === 'True'){
Do Something();
}

</script>
Run Code Online (Sandbox Code Playgroud)

=== 'True'我看来,强迫Razor和JavaScript融洽相处是一种奇怪的攻击。如何重构使用=== true?这不会产生相同的结果。可以用Razor和JavaScript完成吗?

Ehs*_*jad 5

如果属性为bool,则可以按照以下方式检查剃刀的状况:

<script type="text/javascript">
@if (Model.SomeCondition){
@:Do Something();
}
</script>
Run Code Online (Sandbox Code Playgroud)

要么:

<script type="text/javascript">
@if (Model.SomeCondition){
<text>
Do Something();
</text>
}    
</script>
Run Code Online (Sandbox Code Playgroud)

  • 当然,这将评估服务器代码中的布尔值,并且仅在为true时才输出javascript。在某些方面,比将服务器布尔值转换为客户端布尔值更好的解决方案。 (2认同)