Yara
Yara

Reputation: 4565

MVC 3 razor, syntax error

How can I avoid the next logic ? I have the next code in view:

<script type="text/javascript">
        var x = $("#myId1").val();
    @if(Model.IsOptions)
    {
     $('#myId2').click(function () { doSomething(); });
    }
</script>

So, I want execute $('#myId2').. only if 'Model.IsOption' is true. Currently Visual Studio underline it as wrong code.

Upvotes: 2

Views: 302

Answers (2)

oamsel
oamsel

Reputation: 475

Can you try:

@{
    if(Model.IsOptions)
    {
         $('#myId2').click(function () { doSomething(); });
    }
}

Does it work?

Upvotes: 0

Dmitry Osinovskiy
Dmitry Osinovskiy

Reputation: 10118

The code inside @if should be C#, not JavaScript. Razor tries to execute it on server, not on client. To force it to treat it as JavaScript, you should use <text></text> or @:, like this.

<script type="text/javascript">
    var x = $("#myId1").val();
    @if(Model.IsOptions)
    {
        <text>
            $('#myId2').click(function () { doSomething(); });
        </text>
    }
</script>

Upvotes: 6

Related Questions