46

I'd like to execute a piece of JavaScript when a certain condition is true in my view model:

<script type="text/javascript">
    @if (Model.Employees.Count > 1)
    {
        executeJsfunction();
    }
</script>

This code doesn't compile, how should I do this?

1

7 Answers 7

67

Try with this:

<script type="text/javascript">
    @if (Model.Employees.Count > 1)
    {
        @:executeJsfunction();
    }
</script>

Note the "@:"

Sign up to request clarification or add additional context in comments.

2 Comments

It doesn't work, still executes the function unconditionally
@Anton It won't execute if it doesn't render.
25

For multi-line script within the razor conditional block, you can use:

<script type="text/javascript">
    @if (Model.Employees.Count > 1)
    {
       <text>
            executeJsfunctionOne();
            executeJsfunctionTwo();
            executeJsfunctionThree({
               "var_one": true,
               "var_two": false
            });
       </text>
    }
</script>

This can make it cleaner and more practical than adding @: to each line. Everything within the <text></text> blocks is rendered as script.

Comments

22

If you have more complicated JS, you can do the following (script tags, or any tags, within an @if don't need extra escaping):

@if (Model.Employees.Count > 1)
{
    <script type="text/javascript">
        $(function() {
            executeJsfunction();
        });
    </script>
}

1 Comment

Just want to add my $0.02 here -- This works great, and for me the key point was the <script> tag needs to start in the conditional block. If I put the <script> tag out of it, and just had a block of JS in within the conditional, the Razor engine tried to parse it as C# and threw up.
17

Use js if-else block, not C#. Js has its own if-else block.

<script type="text/javascript">
if (@Model.Employees.Count > 1)
{
    executeJsfunction();
}
</script>

1 Comment

Problem with this one is you expose the condition, which may be fine in some cases, but if you need script output for only admins, rather than a less priviledged user, for example, you don't want to expose the functionality.
5

The MVC variables are processed on the server side, the code is always trying to render the Javascript values in order to generate the HTML, please try the code below :

<script type="text/javascript">
@{if (Model.Employees.Count > 1)
    {
        @:executeJsfunction();
    }
}
</script>

I hope this helps.

Comments

0

I know this question posted while ago however I added a new solution as an alternative solution:

you can inject your value from the model into data attribute of selected DOM's element and validate your condition by checking the value of the same data attribute you injected while building your view.

for example, check the following view and the script code snippet how to do it:

<div id="myDiv" data-count="@Model.Employees.Count">
</div>


<script>

  if($("#myDiv").data("count") > 1){
    executeJsfunction();
  }

</script>

Comments

0

In case if you don't want to even render the java script based on some condition

define a section in your layout html

<html> 
<body>  
   @RenderSection("xyz", required: false) 
</body> 
</html>

in your view

@if (Model.Condition)
{
   @section xyz{
      <script>
        $(function () {
             // Your Javascript
         });
    </script>
   }
}

In my case I don't want to expose my Javascript if that feature is not enabled, also it'll reduce the size of the page

Comments

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.