0

I'm trying to use a javascript loop to update data from my c# code. But it only execute the c# method once.

I made a test class :

public class testClass
{
    public static int result;
    public static int nb1;

    public static int add()
    {
        result = result + 1;    
        return result;            
    }    
}

And in my javascript I made this :

<script>    
    setInterval(Testing,3000);
    nb1 = 0;
    function Testing() {                
      nb1 = nb1 + 1; //this is to test that the function really restart after 3 seconds
      document.getElementById('label').innerHTML = nb1 + " | " + @testClass.add(); ; // calling my c# method and print into a html label
    }

And it display this on the page : this is what is displayed on my html page

As you can see the number that show if the javascript function is restarting after 3 seconds works, but the c# method is not updating.

Do you have any solutions ?

haldo
  • 14,512
  • 5
  • 46
  • 52

1 Answers1

1

It seems like you don't really have an understanding how HTML, JS and C# work in unison. When a request is made to your server, It will perform calculations to return a document. This document is presented in HTML, with added logic in the form of JS to compliment it.

When using Razor, you can effectively use C# to help building the document, but not at runtime. If you want your front end document to be able to interact with the backend C# code, you are bound to using sockets(for example SignalR), or AJAX(which would be the most prominent way of asynchronous communication between a web page and a back end).

I will help you understand by stepping through the code with you..

Your razor page will start building. at one point it will detect the following line:

document.getElementById('label').innerHTML = nb1 + " | " + @testClass.add(); ; // calling my c# method and print into a html label

this is where it will call on the C# method, convert it to a value, and put the value in the JS code, so when the document gets sent to the client (your webbrowser) the code will look as follows:

document.getElementById('label').innerHTML = nb1 + " | " + {THE CALCULATED VALUE} ; // calling my c# method and print into a html label

I will refer you to this answer. Where it is explained how to do what you are trying to do.

Dennis Lukas
  • 483
  • 2
  • 6
  • 20