How to use javascript code inside if Razor?

Asked

Viewed 580 times

1

In my view, I have code following:

<script type="text/javascript">

    @if(Model.File == true)
    {
       //Como usar javascript aqui ?
       //Exemplo:
       $("#target").click(function() {
        alert("Handler for .click() called.");
       });

    }

</script>
  • I don’t really understand this @ and I’m very layy in javascript, but why in the first if you put @outside and then you used inside the condition? Sure that’s not the problem?

  • @Francisco, updated post, please look.

1 answer

2


Use the pseudo-element <text> to accomplish what you want. Your code would look like this:

<script type="text/javascript">

    @if(Model.File == true)
    {
       //Como usar javascript aqui ?
       //Exemplo:
      <text>
           $("#target").click(function() {
             alert("Handler for .click() called.");
           });
      </text>
    }

</script>

Another way would be to use the if out of script, this way:

@if(Model.File == true)
{
    <script type="text/javascript">
        //Como usar javascript aqui ?
        //Exemplo:
        $("#target").click(function() {
            alert("Handler for .click() called.");
        });
    </script>
}
  • Using if javascript is also a valid proposal, or not?

  • Randrade what is the most correct form ? The first example or second ?

  • @Matheusmiranda Depends a lot on what you want. Razor in Javascript is not something to match like this. In your example, specifically, me I think I’d better do the if out of the script, so you avoid loading unnecessary code to the View. Now, if you have more codes, it may be that the <text> be better.

  • @Francisco Yes, and even more used, because you only use what you need.

  • Thanks @Randrade, solved my problem.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.