2016-02-24

How to Conditionally Execute JavaScript in Razor View

You would like to execute a piece of JavaScript only when some conditions in MVC model are met. My first (wrong) attempt was:

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

... and the code above did not compile. I finally realize that the solution is to use @: predicate in front of JavaScript call.

<script type="text/javascript">
    @if (Model.Employees.Count > 1)
    {
        @:executeJsfunction();
    }
</script>
While this is OK for JavaScript onliners, you need to use <text> tag instead of @: if you want to include more than one line.

No comments:

Post a Comment