在 JavaScript 条件语句中使用 Razor 语法

Using Razor Syntax within JavaScript Conditional Statment

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

<script type="text/javascript">

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

</script>

=== 'True' 对我来说似乎是一个奇怪的技巧,它迫使 Razor 和 JavaScript 相处。我如何重构才能使用 === true?这不会给出相同的结果。这可以用 Razor 和 JavaScript 来完成吗?

假设SomeCondition是一个字符串,去掉引号,使其符合javascript的布尔值的小写形式

<script language="javascript">
    // just to be clear this is javascript, not server code
    if (@Model.SomeCondition.ToLowerInvariant()){
        .. // 
    }
</script>

但是,如果 SomeCondition 在服务器代码中是布尔值,您需要先将其转换为字符串并将其设为小写

<script language="javascript">
    // just to be clear this is javascript, not server code
    if (@Model.SomeCondition.ToString().ToLowerInvariant()){
        .. // 
    }
</script>

如果属性是bool,您可以按照以下方式检查剃须刀:

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

或:

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

只需在 c#/razor 中编写 if 语句,并在其中执行 javascript。

示例:

@if(boolVariable)
{
    <script>
        //javascript here
    </script>
}