0

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?

Willy
  • 9,848
  • 22
  • 141
  • 284
  • 2
    may be not possible, you can refer this link https://stackoverflow.com/questions/28317182/how-to-pass-a-value-to-razor-variable-from-javascript-variable – Hien Nguyen Feb 04 '20 at 00:56
  • 1
    Does this answer your question? [How to pass a value to razor variable from javascript variable?](https://stackoverflow.com/questions/28317182/how-to-pass-a-value-to-razor-variable-from-javascript-variable) – Abdelrahman Gobarah Feb 04 '20 at 03:46
  • Are you sure the `@myVariable` is not being set? – Bilal Ahmed Feb 04 '20 at 08:17
  • @AbdelrahmanGobarah Yes, it helps me. – Willy Feb 05 '20 at 20:26
  • @BilalAhmed I have checked the code generated in the client side and as Abdelrahman says it is parsed as true = false, so not possible to assign a razor variable with a javascript variable. – Willy Feb 05 '20 at 20:28

1 Answers1

1

@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>
Abdelrahman Gobarah
  • 1,544
  • 2
  • 12
  • 29