5

Can I write my razor code in javascript like this:

<script type="text/javascript">
    $(document).ready(function () {
        alert("test");

        @if (Model != null)
        {
            foreach (var item in Model)
            {
                alert(item);
            }
        }
    });
</script>

I'm getting a error that alert is not defined

2 Answers 2

8
<script type="text/javascript">
    $(document).ready(function () {
        alert("test");
        @if (Model != null) {            
            foreach (var item in Model) {
                @:alert(item);
            }
        }
    });
</script>

Since you are inside the razor code block, you need to tell razor alert() is not a part of razor code block via @:

Alternatively, you can use <text> element.

<text>
   alert(item);
</text>
Sign up to request clarification or add additional context in comments.

Comments

1
foreach (var item in Model)
{
     <text>
     alert(item);
     </text>
}

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.