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?

5
  • 2
    may be not possible, you can refer this link stackoverflow.com/questions/28317182/… Commented Feb 4, 2020 at 0:56
  • 1
    Does this answer your question? How to pass a value to razor variable from javascript variable? Commented Feb 4, 2020 at 3:46
  • Are you sure the @myVariable is not being set? Commented Feb 4, 2020 at 8:17
  • @AbdelrahmanGobarah Yes, it helps me. Commented Feb 5, 2020 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. Commented Feb 5, 2020 at 20:28

1 Answer 1

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>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.