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?
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>
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With