Search code examples
razorrazor-pages

What is the Razor syntax for adding a C# condition in the script tag


I have a script tag in my Razor cshtml file. I would like to conditionally add Javascript based on a property in my model.

Here is what I have done. Both attempts work. But is there a better way, e.g. what if my Javascript is more than a single line of code?

Attempt 1

@section scripts{
<script>
    $(document).ready(function() {
    @if (Model.IsAdding)
    {
        @Html.Raw("window.scrollTo(0, document.body.scrollHeight);")
        ;
    }
</script>
}

Attempt 2

@section scripts{
<script>
    $(document).ready(function() {
       @(Model.IsAdding? "window.scrollTo(0, document.body.scrollHeight);" : "")
    });
</script>
}

Solution

  • You can use the <text></text> tag

    @section scripts {
        <script>
            $(document).ready(function () {
                @if (Model.IsAdding)
                {
                    <text>
                        // add your javascript code here
                        alert("test");
                    </text>
                }
            }
        </script>
    }