Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

possible to 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'm getting a error that alert is not defined

like image 816
gurehbgui Avatar asked Apr 10 '13 11:04

gurehbgui


Video Answer


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 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>
like image 141
emre nevayeshirazi Avatar answered Sep 20 '22 07:09

emre nevayeshirazi


foreach (var item in Model)
{
     <text>
     alert(item);
     </text>
}
like image 33
karaxuna Avatar answered Sep 23 '22 07:09

karaxuna