简体   繁体   中英

Access Static Property Values From Code Behind Jquery/Javascript

I have to read the Max value and Percent value into jquery function. I have tried reading these values into hidden variable and Session variable on page load which returns 0 always. These are my properties:

    public static int Max { get; set; }
    public static int Percent { get; set; }

Here is my Codebehind:

      [WebMethod]
      public static string Test()
      { 
          var y = 0;
          var max = 100000;
          Max = max;
          for(int i = 0; i < max; i++)
          {
              y++;
              Percent = y++; 
          }
          if (y > max)
              return "Success";
          else
            return "Fail";
      }

This is my ajax call on button click. I am trying to read the max value and percent value for each i with another function. I am not sure how to call those values into another function.

<asp:Button ID="btnGetData" runat="server" Text="Get Data" />

   $(document).ready(function () {
     $$('btnGetData').click(function () {
         function readValues();
         $.ajax({
             type: 'POST',
             url: 'Test.aspx/Test',
             data: "{}",
             contentType: "application/json; charset=utf-8",
             dataType: "json",
             async: true,
             success: function (Result) {
                 alert(Result.d);
             },
             error: function (Result) {
                 alert('Error!');
             }

         });
     });
 });
function readValues(){
 var t = <%= Max%>;
 var p = <%= Percent%>;  //This has to be updated every few seconds until 
                             //the for loop is finished.
}

I guess what you are trying to acheive is similar to this Question: Simple BackgroundWorker is not updating label on web page

Basically, your options are:

  • Re-architect your server-side code so the operation starts with the first call (and returns immediately), then the front end can call a different function/endpoint to see what the current progress is and report that (probably by using a timer once a second or something)
  • Use something to enable two-way communications (eg SignalR) so the server can report its progress back to the client.

Either of these is probably a bit too involved for a straightforward answer on StackOverflow. I suggest trying to put together something around these suggestions then coming back if you have problems.

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