简体   繁体   中英

JavaScript code calling codebehind function only one time

I have a JavaScript function which is not calling a function in codebehind more than once. I have debugged it and I can confirm that it is not calling more than once. Is it something that I am missing?

JavaScript code:

function loader() {
            for(var i=0;i<<%=array1.Length%>;i++)
            {<%increment();%>;
             alert(<%=counter%>);
            }

        }

codebehind function:

public int counter = -1;
       public void increment()
       { counter++; }

You can't really intertwine your client-side Javascript code and your server-side C# code like this. Basically, once the rendering has been done on your page, you aren't really going to access the server until either a PostBack has occurred or your use AJAX to call an exposed WebMethod .

It'll call it once when the page initially renders, otherwise, you would need to use one of the other techniques.

WebMethod Approach

You could accomplish this as I mentioned earlier by taking advantage of a WebMethod , which would involve you creating a method in your code-behind that looks something like this :

[WebMethod]
public static void IncrementCounter()
{
     // Since you want to return the incremented value, use ++counter
     return ++counter;
}

And then you would need to add a reference in your ASPX page to the jQuery library, which will be used to handle performing AJAX calls to access this server-side method :

<script src="https://code.jquery.com/jquery-2.1.4.js"></script>
<script>
    // This will ensure that your jQuery code is ready to run
    $(function(){
          // When the page is ready, call your loading function
          loader();
    });

    function loader() {
        for(var i=0; i< <%=array1.Length%>; i++){
            // This will call your WebMethod
            $.post('YourPage.aspx/IncrementCounter', function(count){
                  // count will contain the counter value
                  alert(count);
            });
        }
    }
</script>

As @RonWilliams says, that code is only executed at the begining, when the aspx is rendering, and not anymore.

The only way the code is executed in the form you write it, is for example inside a asp:Repeater or inside a asp:TemplateField in a GridView .

If you want to call a server-side functions try with AJAX or with Page Methods

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM