Willy
Willy

Reputation: 10638

Update Razor variable from within a javascript function

I am a noob in using Razor and now I am trying to update a Razor variable from within a javascript function. For example:

@{
    bool myVariable = false;
}

<script type="text/javascript">

    function Foo() {
       if (some_condition)
       {
          @myVariable = true;
       }
    }

</script>

@if (myVariable)
{
   <div>
      <!-- stuff -->
   </div>
}

Is that possible? If so, how can I do it?

Upvotes: 0

Views: 1365

Answers (1)

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

@myVariable is a server-side variable it get's it's value from server before rendering the page

@myVariable will print the value of the variable not assign to it,

so the output of @myVariable = true; will be

false = true;

use ajax to get content from server

@{
    bool myVariable = false;
}

<script type="text/javascript">

    function Foo() {
       if (some_condition)
       {
          $('#newContent').load('/News/GetLatest/10'); // call ajax to get content
       }
    }

</script>

   <div id="newContent">
      <!-- stuff -->
   </div>

or you can only show the div if condition is true on the client side

@{
    bool myVariable = false;
}

<script type="text/javascript">
    var showContent = @myVariable; // false

    function Foo() {
       if (some_condition)
       {
          showContent = true;
          $('#newContent').show(); // show it
       }
    }

</script>

   <div id="newContent" style="display: none;"> <!-- hidden by default -->
      <!-- stuff -->
   </div>

Upvotes: 1

Related Questions