David Vogel
David Vogel

Reputation: 465

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?

Upvotes: 5

Views: 3987

Answers (3)

Ehsan Sajjad
Ehsan Sajjad

Reputation: 62488

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>

Upvotes: 9

Ilnetd
Ilnetd

Reputation: 89

Just write the if satement in c#/razor with the javascript you want to execute in there.

Example:

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

Upvotes: 0

Jamiec
Jamiec

Reputation: 136074

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>

Upvotes: 2

Related Questions