admin管理员组

文章数量:1287627

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?

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?

Share Improve this question edited Jun 2, 2015 at 15:36 David Vogel asked Jun 2, 2015 at 15:31 David VogelDavid Vogel 4658 silver badges23 bronze badges 1
  • 6 Mixing Razor and Javascript is a bad idea. You should separate data from code using data-* attributes. – SLaks Commented Jun 2, 2015 at 15:33
Add a ment  | 

3 Answers 3

Reset to default 9

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>

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

Example:

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

本文标签: cUsing Razor Syntax within JavaScript Conditional StatmentStack Overflow