$(document).ready(fu...">

Can I write razor code in javascript?

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 get an error that is not defined

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

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

Alternatively you can use an element <text>.

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

All Articles