Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Razor Syntax within JavaScript Conditional Statment

In an index.cshtml I have the following working code similar to:

<script type="text/javascript">

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

</script>

The === 'True' seems like an odd hack to me to force Razor and JavaScript to get along. How can I refactor to use === true? This doesn't give the same result. Can this be done with Razor and JavaScript?

like image 838
David Vogel Avatar asked Jan 08 '23 06:01

David Vogel


2 Answers

If the property isbool, you can check in razor if condition following way:

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

or:

<script type="text/javascript">
@if (Model.SomeCondition){
<text>
Do Something();
</text>
}    
</script>
like image 134
Ehsan Sajjad Avatar answered Jan 17 '23 22:01

Ehsan Sajjad


Assuming SomeCondition is a string, remove the quotes, and make it conform to the lowercase form of javascript's booleans

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

If, however SomeCondition is a boolean in server code, you need to first convert to a string and make it lowercase

<script language="javascript">
    // just to be clear this is javascript, not server code
    if (@Model.SomeCondition.ToString().ToLowerInvariant()){
        .. // 
    }
</script>
like image 23
Jamiec Avatar answered Jan 17 '23 21:01

Jamiec