5

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?

1
  • 6
    Mixing Razor and Javascript is a bad idea. You should separate data from code using data-* attributes. Commented Jun 2, 2015 at 15:33

3 Answers 3

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>
Sign up to request clarification or add additional context in comments.

1 Comment

This will, of course, evaluate the boolean in server code and only output the javascript if true. In some ways a better solution than turning a server boolean into a client-side boolean.
2

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>

Comments

0

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

Example:

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

2 Comments

That's fine if that's the only JavaScript you want to run, but if it's part of a larger block it doesn't really work
Well, assuming this was going inside of already declared <script> tags, just use ViewContext.Writer.Write("javascript here"). This isn't a good scenario to be in to begin with, this is just a solution without refactoring everything.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.