locked
WebMethod Doesn't Get Called on Debug RRS feed

  • Question

  • User-698989805 posted

    I am trying to insert data using jQuery and have done that earlier. But for the time being, I am doing this after a long time. Now the issue is I am trying to do debugging with browser and can see that the Ajax call actually doesn't get called or it doesn't even go to the url section of the Ajax call. So here is my scenario: I've a table data and every row is associated with a button. If I click on the button, the associated row data will be inserted into database table (But here I put break-point in the debugger to check if the web method is called). So this is what I've tried:

    <title>Tutorial - Sample App</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <form id="form1" runat="server">
    <div>
      <asp:Label ID="lblPersons" runat="server"></asp:Label>
    </div>
    </form>
    
     <script>
        $(".click").click(function () {
            var $row = $(this).closest("tr");    //Get the row
            var $text = $row.find(".val").text(); //Get the text or value
    
            alert($text);
    
            debugger;
            var persons = new Array();
            var person = {};
    
            person.name = $row.find(".val").text();
            persons.push(person);
    
            //The Ajax call here
            $.ajax({
                type: "POST",
                url: "/SampleWebForm.aspx/InsertPersons", //This isn't called actually and keeping the code in the same page - SampleWebForm.aspx
                data: JSON.stringify(persons),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert(data + " record(s) inserted.");
                }
            });
        });
    </script>

    Then the C# section here:

    protected void Page_Load(object sender, EventArgs e)
    {
       lblPersons.Text = Concatenate();
    }
    
    public class Person
    {
       public string name { get; set; }
       public string age { get; set; }
    }
    
    public List<Person> GetPersons()
    {
       List<Person> lst = new List<Person>
       {
          new Person { name = "John", age = "20" },
          new Person { name = "Jack", age = "30" }
       };
    
       return lst;
    }
    
    public string Concatenate()
    {
       string data = "";
              data += "<table id = 'tblPersons'" +
                      "<thead>" +
                      "<tr class='ui-widget-header'>" +
                      "<th>Name</th>" +
                      "<th>Age</th>" +
                      "</tr>" +
                      "</thead>" +
                      "<tbody>" +
                      "";
                      foreach (var item in GetPersons())
                      {
              data +=   "<tr><td class='val'><span>" + item.name + "</span></td>" +
                        "<td>" + item.age + "</td><br/>" +
                        "<td><button type = 'button' class = 'click' id = 'btnSave'>Click Here</button><td><tr>" +
                        "</td>";
                      }
              data += "" +
                      "</tbody>" +
                      "</table>";
    
        return data;
    }
    
    [WebMethod]
    public string InsertPersons(Person persons) //This is the method that's supposed to be hit while debugging but doesn't
    {
       string name = "";
       name = persons.name;
    
       return name;
    }

    Thursday, November 1, 2018 2:06 PM

Answers

  • User475983607 posted

    Web method inside a web form must be static.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 1, 2018 3:16 PM
  • User475983607 posted

    TechView

    Already did so but doesn't get called I mean the method.

    There is no indication the web method is fixed.  Use dev tools to debug the code (F12) and look for errors.

    TechView

    I've done two things to make it work but in vain. In the RouteConfig file, did this:

    settings.AutoRedirectMode = RedirectMode.Permanent;

    To

    settings.AutoRedirectMode = RedirectMode.Off;

    I'm not following your thought process and there is not provided enough code to guess.  If the route config looks like this...

        public static class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                var settings = new FriendlyUrlSettings();
                settings.AutoRedirectMode = RedirectMode.Permanent;
                routes.EnableFriendlyUrls(settings);
            }
        }

    Then need fix your URL by removing the .aspx

    url: "SampleWebForm/InsertPersons"

    If your route config looks like this...

            public static void RegisterRoutes(RouteCollection routes)
            {
                var settings = new FriendlyUrlSettings();
                //settings.AutoRedirectMode = RedirectMode.Permanent;
                settings.AutoRedirectMode = RedirectMode.Off;
                routes.EnableFriendlyUrls(settings);
            }

    Then the URL can have the .aspx extension and look like this...

    url: "SampleWebForm.aspx/InsertPersons",

    Keep in mind, that original URL is looking in the application root.  If SamplesWebForms.aspx is within a folder then the the URL will not be found.

    url: "/SampleWebForm.aspx/InsertPersons",

    Lastly, there are not class, use-address, in the posted code.  So this click event will never fire...

        $(".use-address").click(function () {
            var $row = $(this).closest("tr");    //Get the row
            var $text = $row.find(".val").text(); //Get the text or value

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 1, 2018 5:17 PM
  • User839733648 posted

    Hi TechView,

    According to your description and code, I've found that the key point is the type of the parameter is not consistent.

    persons in your JS code is an array

    persons in your webmethod is an object.

    So there will be errors when running the code.

    I suggest that you could modify the type of the persons in your JS code or in your webmethod.

    And you should pay attention that the format of passing parameter is like:

     data: JSON.stringify({ persons: persons })

    Here are the two ways modifying your code.

    • Modifying webmethod:

    JS.

            $(function () {
                $("#btnSave").click(function () {
                    var $row = $(this).closest("tr");    //Get the row
                    var $text = $row.find(".val").text(); //Get the text or value
                    alert($text);
                    var persons = new Array();
                    var person = {};
                    person.name = $row.find(".val").text();
                    persons.push(person);
                    $.ajax({
                        type: "POST",
                        url: "InsertWebMethod.aspx/InsertPersons", //This isn't called actually and keeping the code in the same page - SampleWebForm.aspx
                        data: JSON.stringify({ persons: persons }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            alert(data + " record(s) inserted.");
                        }
                    });
                });
            })

    Webmethod.

            public static string InsertPersons(List<Person> persons) //This is the method that's supposed to be hit while debugging but doesn't
            {
                string name = "";
                //name = persons.name;
                return name;
            }
    • Modifying js:

    JS.

        <script>
            $(function () {
                $("#btnSave").click(function () {
                    var $row = $(this).closest("tr");    //Get the row
                    var $text = $row.find(".val").text(); //Get the text or value
                    alert($text);
                    var persons = { name: $text };
                    $.ajax({
                        type: "POST",
                        url: "InsertWebMethod.aspx/InsertPersons", //This isn't called actually and keeping the code in the same page - SampleWebForm.aspx
                        data: JSON.stringify({ 'persons': persons }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            alert(data + " record(s) inserted.");
                        }
                    });
                });
            })
    
        </script>

    Webmethod.

            [WebMethod]
            public static string InsertPersons(Person persons) //This is the method that's supposed to be hit while debugging but doesn't
            {
                string name = "";
                name = persons.name;
                return name;
            }

    Best Regards,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 2, 2018 10:14 AM
  • User475983607 posted

    So for the above code, I've one data set. What I am doing is if there is no parameter, then it should fetch all data from the server and if parameter exists, then load expected data. By default, it'll fetch all data, so my question is when I pass a parameter, does it load the data set again or works on the existing one with Ajax call?? So hoping the same works for Angular and would like to have advice to clarify - Thanks.

    The code shown builds populates and HTML table from an unknown GetPerson() method a filtered result of the same. 

    Assuming that the AJAX code functions properly, making an HTTP request will result in an HTTP response.  It's up to you to design code that updates the DOM. 

    One more thing: In the same code, if I make it work for the parameter part only like it'll fetch data from server-side with Ajax call only passing parameters, then what will be the condition? Will it fetch data every time from the serve or from jQuery caching mechanism in the browser? I've tried to study these things a bit but willing to know more.

    The code shown in the last post does not make logical sense as the string parameter, str, is used as a flag.  Usually a bool is a flag.   Regardless, Is there any reason why you don't simply run the code through the debugger to verify the code functions are expected?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, November 4, 2018 5:07 PM
  • User475983607 posted

    @mgebhard! The code runs fine and checked using the debugger as well. But I am willing to know more on client-side functionalities rather than server-side. More interested, how Ajax actually works on the retrieved data and how many times it calls the server.

    If the code has not changed, the AJAX function is invoked when the user clicks an element with the "click" class.   The AJAX function within the click handlers does an HTTP POST request to the Web Method.

     <script>
        $(".click").click(function () {

    It is a little confusing that you do not know how the code works or when the AJAX is invoked.  Is this code that you copied from somewhere and are asking the community to explain the flow?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, November 4, 2018 6:58 PM
  • User475983607 posted

    Know a bit but was just confirming. I've tried to study these two and more interested to know more on jQuery caching. My goal is how I can improve the performance of the Ajax call.

    jQuery Caching - 01

    jQuery Caching - 02

    jQuery is an API.  Caching is a programming technique to persists data that does not change often.

    The first link is a jQuery Cache API.  If you want to learn how to use the API then read the documentation.  Keep in mind there is no indication whatsoever that you are even using the API in your code.

    The second link is about storing data in variables or the DOM.  This is normal everyday basic programming.

    So I am planning to use the caching in the following code:

     $(function () {
        $("#btnSave").click(function () {
             var $row = $(this).closest("tr");    
             var $text = $row.find(".val").text(); 
             alert($text);
                    
             var persons = new Array();
             var person = {};
             person.name = $row.find(".val").text();
                 
             persons.push(person);
                    
             $.ajax({
                    type: "POST",
                    url: "ShowData.aspx/GetData",
                    data: JSON.stringify({ persons: persons }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                    alert(data + " record(s) inserted.");
                  }
             });
        });
    })

    So could you provide me an example on caching with Ajax call? I am trying to figure how I can do so, though not sure if I could make it for the above Ajax call with caching - Thanks.

    If you are trying to cache the HTTP request then see caching in ASP.NET. 

    https://msdn.microsoft.com/en-us/library/xsbfdd8c.aspx

    If you are asking about the cache property in the jQuery AJAX function,then see the reference docs.

    http://api.jquery.com/jquery.ajax/

    cache (default: true, false for dataType 'script' and 'jsonp')
    Type: Boolean
    If set to false, it will force requested pages not to be cached by the browser. Note: Setting cacheto false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

    If you are trying to build a custom cache feature then you left out the most important piece requirement which is what are you caching and why? 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 5, 2018 2:54 PM

All replies

  • User475983607 posted

    Web method inside a web form must be static.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 1, 2018 3:16 PM
  • User-698989805 posted

    Already did so but doesn't get called I mean the method. I've done two things to make it work but in vain. In the RouteConfig file, did this:

    settings.AutoRedirectMode = RedirectMode.Permanent;

    To

    settings.AutoRedirectMode = RedirectMode.Off;

    Finally, the below:

    url: '<%= ResolveUrl("SampleWebForm.aspx/InsertPersons") %>'

    Thursday, November 1, 2018 3:24 PM
  • User475983607 posted

    TechView

    Already did so but doesn't get called I mean the method.

    There is no indication the web method is fixed.  Use dev tools to debug the code (F12) and look for errors.

    TechView

    I've done two things to make it work but in vain. In the RouteConfig file, did this:

    settings.AutoRedirectMode = RedirectMode.Permanent;

    To

    settings.AutoRedirectMode = RedirectMode.Off;

    I'm not following your thought process and there is not provided enough code to guess.  If the route config looks like this...

        public static class RouteConfig
        {
            public static void RegisterRoutes(RouteCollection routes)
            {
                var settings = new FriendlyUrlSettings();
                settings.AutoRedirectMode = RedirectMode.Permanent;
                routes.EnableFriendlyUrls(settings);
            }
        }

    Then need fix your URL by removing the .aspx

    url: "SampleWebForm/InsertPersons"

    If your route config looks like this...

            public static void RegisterRoutes(RouteCollection routes)
            {
                var settings = new FriendlyUrlSettings();
                //settings.AutoRedirectMode = RedirectMode.Permanent;
                settings.AutoRedirectMode = RedirectMode.Off;
                routes.EnableFriendlyUrls(settings);
            }

    Then the URL can have the .aspx extension and look like this...

    url: "SampleWebForm.aspx/InsertPersons",

    Keep in mind, that original URL is looking in the application root.  If SamplesWebForms.aspx is within a folder then the the URL will not be found.

    url: "/SampleWebForm.aspx/InsertPersons",

    Lastly, there are not class, use-address, in the posted code.  So this click event will never fire...

        $(".use-address").click(function () {
            var $row = $(this).closest("tr");    //Get the row
            var $text = $row.find(".val").text(); //Get the text or value

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, November 1, 2018 5:17 PM
  • User839733648 posted

    Hi TechView,

    According to your description and code, I've found that the key point is the type of the parameter is not consistent.

    persons in your JS code is an array

    persons in your webmethod is an object.

    So there will be errors when running the code.

    I suggest that you could modify the type of the persons in your JS code or in your webmethod.

    And you should pay attention that the format of passing parameter is like:

     data: JSON.stringify({ persons: persons })

    Here are the two ways modifying your code.

    • Modifying webmethod:

    JS.

            $(function () {
                $("#btnSave").click(function () {
                    var $row = $(this).closest("tr");    //Get the row
                    var $text = $row.find(".val").text(); //Get the text or value
                    alert($text);
                    var persons = new Array();
                    var person = {};
                    person.name = $row.find(".val").text();
                    persons.push(person);
                    $.ajax({
                        type: "POST",
                        url: "InsertWebMethod.aspx/InsertPersons", //This isn't called actually and keeping the code in the same page - SampleWebForm.aspx
                        data: JSON.stringify({ persons: persons }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            alert(data + " record(s) inserted.");
                        }
                    });
                });
            })

    Webmethod.

            public static string InsertPersons(List<Person> persons) //This is the method that's supposed to be hit while debugging but doesn't
            {
                string name = "";
                //name = persons.name;
                return name;
            }
    • Modifying js:

    JS.

        <script>
            $(function () {
                $("#btnSave").click(function () {
                    var $row = $(this).closest("tr");    //Get the row
                    var $text = $row.find(".val").text(); //Get the text or value
                    alert($text);
                    var persons = { name: $text };
                    $.ajax({
                        type: "POST",
                        url: "InsertWebMethod.aspx/InsertPersons", //This isn't called actually and keeping the code in the same page - SampleWebForm.aspx
                        data: JSON.stringify({ 'persons': persons }),
                        contentType: "application/json; charset=utf-8",
                        dataType: "json",
                        success: function (data) {
                            alert(data + " record(s) inserted.");
                        }
                    });
                });
            })
    
        </script>

    Webmethod.

            [WebMethod]
            public static string InsertPersons(Person persons) //This is the method that's supposed to be hit while debugging but doesn't
            {
                string name = "";
                name = persons.name;
                return name;
            }

    Best Regards,

    Jenifer

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, November 2, 2018 10:14 AM
  • User-698989805 posted

    Thanks a lot @Jenifer. I was to able to figure out later and the same thing I noticed. Though I would like to know an info on jQuery as well on Angular. This may be not relevant with the current thread and not willing to open a new one.

    Me and one of my friend were arguing on jQuery data loading. So my point is, if we have one data set and jQuery loads that, then it loads that data set once. Finally jQuery uses its caching mechanism to get it done for the rest. So for the following code:

    public string Concatenate(string str)
    {
       string data = "";
       if(str != "")
       {
          data += "<table id = 'tblPersons'" +
                  "<thead>" +
                  "<tr class='ui-widget-header'>" +
                  "<th>Name</th>" +
                  "<th>Age</th>" +
                  "</tr>" +
                  "</thead>" +
                  "<tbody>" +
                  "";
                  foreach (var item in GetPersons().where(m => m.Id != ""))
                  {
           data +=   "<tr><td class='val'><span>" + item.name + "</span></td>" +
                     "<td>" + item.age + "</td><br/>" +
                     "<td><button type = 'button' class = 'click' id = 'btnSave'>Click Here</button><td><tr>" +
                     "</td>";
                  }
          data += "" +
                  "</tbody>" +
                  "</table>";
        }
        else
        {
           data += "<table id = 'tblPersons'" +
                  "<thead>" +
                  "<tr class='ui-widget-header'>" +
                  "<th>Name</th>" +
                  "<th>Age</th>" +
                  "</tr>" +
                  "</thead>" +
                  "<tbody>" +
                  "";
                  foreach (var item in GetPersons())
                  {
           data +=   "<tr><td class='val'><span>" + item.name + "</span></td>" +
                     "<td>" + item.age + "</td><br/>" +
                     "<td><button type = 'button' class = 'click' id = 'btnSave'>Click Here</button><td><tr>" +
                     "</td>";
                  }
          data += "" +
                  "</tbody>" +
                  "</table>";
        }
    
        return data;
    }

    So for the above code, I've one data set. What I am doing is if there is no parameter, then it should fetch all data from the server and if parameter exists, then load expected data. By default, it'll fetch all data, so my question is when I pass a parameter, does it load the data set again or works on the existing one with Ajax call?? So hoping the same works for Angular and would like to have advice to clarify - Thanks.

    One more thing: In the same code, if I make it work for the parameter part only like it'll fetch data from server-side with Ajax call only passing parameters, then what will be the condition? Will it fetch data every time from the serve or from jQuery caching mechanism in the browser? I've tried to study these things a bit but willing to know more.

    Sunday, November 4, 2018 4:43 PM
  • User475983607 posted

    So for the above code, I've one data set. What I am doing is if there is no parameter, then it should fetch all data from the server and if parameter exists, then load expected data. By default, it'll fetch all data, so my question is when I pass a parameter, does it load the data set again or works on the existing one with Ajax call?? So hoping the same works for Angular and would like to have advice to clarify - Thanks.

    The code shown builds populates and HTML table from an unknown GetPerson() method a filtered result of the same. 

    Assuming that the AJAX code functions properly, making an HTTP request will result in an HTTP response.  It's up to you to design code that updates the DOM. 

    One more thing: In the same code, if I make it work for the parameter part only like it'll fetch data from server-side with Ajax call only passing parameters, then what will be the condition? Will it fetch data every time from the serve or from jQuery caching mechanism in the browser? I've tried to study these things a bit but willing to know more.

    The code shown in the last post does not make logical sense as the string parameter, str, is used as a flag.  Usually a bool is a flag.   Regardless, Is there any reason why you don't simply run the code through the debugger to verify the code functions are expected?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, November 4, 2018 5:07 PM
  • User-698989805 posted

    @mgebhard! The code runs fine and checked using the debugger as well. But I am willing to know more on client-side functionalities rather than server-side. More interested, how Ajax actually works on the retrieved data and how many times it calls the server.

    Sunday, November 4, 2018 5:41 PM
  • User475983607 posted

    @mgebhard! The code runs fine and checked using the debugger as well. But I am willing to know more on client-side functionalities rather than server-side. More interested, how Ajax actually works on the retrieved data and how many times it calls the server.

    If the code has not changed, the AJAX function is invoked when the user clicks an element with the "click" class.   The AJAX function within the click handlers does an HTTP POST request to the Web Method.

     <script>
        $(".click").click(function () {

    It is a little confusing that you do not know how the code works or when the AJAX is invoked.  Is this code that you copied from somewhere and are asking the community to explain the flow?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Sunday, November 4, 2018 6:58 PM
  • User-698989805 posted

    Thanks a lot @mgebhard. You can say so - Know a bit but was just confirming. I've tried to study these two and more interested to know more on jQuery caching. My goal is how I can improve the performance of the Ajax call.

    jQuery Caching - 01

    jQuery Caching - 02

    So I am planning to use the caching in the following code:

     $(function () {
    var $get = $("#btnGet"); //Say using this, will improve the performance of a web app as it uses caching and it'll continue to use the cache unless there's any change on the data
    $get.click(function () { var $row = $(this).closest("tr"); var $text = $row.find(".val").text(); alert($text); var persons = new Array(); var person = {}; person.name = $row.find(".val").text(); persons.push(person); $.ajax({ type: "POST", url: "ShowData.aspx/GetData", data: JSON.stringify({ persons: persons }), contentType: "application/json; charset=utf-8", dataType: "json", success: function (data) { alert(data + " record(s) inserted."); } }); });

    $get.hide(); //Finally ends it here })

    So could you provide me an example on caching with Ajax call? I am trying to figure how I can do so, though not sure if I could make it for the above Ajax call with caching - Thanks.

    Monday, November 5, 2018 2:32 PM
  • User475983607 posted

    Know a bit but was just confirming. I've tried to study these two and more interested to know more on jQuery caching. My goal is how I can improve the performance of the Ajax call.

    jQuery Caching - 01

    jQuery Caching - 02

    jQuery is an API.  Caching is a programming technique to persists data that does not change often.

    The first link is a jQuery Cache API.  If you want to learn how to use the API then read the documentation.  Keep in mind there is no indication whatsoever that you are even using the API in your code.

    The second link is about storing data in variables or the DOM.  This is normal everyday basic programming.

    So I am planning to use the caching in the following code:

     $(function () {
        $("#btnSave").click(function () {
             var $row = $(this).closest("tr");    
             var $text = $row.find(".val").text(); 
             alert($text);
                    
             var persons = new Array();
             var person = {};
             person.name = $row.find(".val").text();
                 
             persons.push(person);
                    
             $.ajax({
                    type: "POST",
                    url: "ShowData.aspx/GetData",
                    data: JSON.stringify({ persons: persons }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                    alert(data + " record(s) inserted.");
                  }
             });
        });
    })

    So could you provide me an example on caching with Ajax call? I am trying to figure how I can do so, though not sure if I could make it for the above Ajax call with caching - Thanks.

    If you are trying to cache the HTTP request then see caching in ASP.NET. 

    https://msdn.microsoft.com/en-us/library/xsbfdd8c.aspx

    If you are asking about the cache property in the jQuery AJAX function,then see the reference docs.

    http://api.jquery.com/jquery.ajax/

    cache (default: true, false for dataType 'script' and 'jsonp')
    Type: Boolean
    If set to false, it will force requested pages not to be cached by the browser. Note: Setting cacheto false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.

    If you are trying to build a custom cache feature then you left out the most important piece requirement which is what are you caching and why? 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Monday, November 5, 2018 2:54 PM
  • User-698989805 posted

    I was actually following this link and believe, this will serve what I expected for custom caching mechanism. Here's the link:

    Custom Caching

    So I tried something like this as follows:

    [WebMethod]
    public static string Concatenate()
    {
       string data = "";
              data += "<table id = 'tblPersons'" +
                      "<thead>" +
                      "<tr class='ui-widget-header'>" +
                      "<th>Name</th>" +
                      "<th>Age</th>" +
                      "</tr>" +
                      "</thead>" +
                      "<tbody>" +
                      "";
                      foreach (var item in GetPersons())
                      {
              data +=   "<tr><td class='val'><span>" + item.name + "</span></td>" +
                        "<td>" + item.age + "</td><br/>" +
                        "<td><button type = 'button' class = 'click' id = 'btnSave'>Click Here</button><td><tr>" +
                        "</td>";
                      }
              data += "" +
                      "</tbody>" +
                      "</table>";
    
        return data;
    }

    So my criteria is if there is no newly added data in the list of object GetPersons(), then the posted data should be retrieved from the cache or if there is anything new, then it'll request from the server. In the front-end, I believe, it should be something like this in short:

    var $persons= $('#lblPersons');

    if ($persons.data('ajax-cache').length == 0) { //If new data, then request from the server $.ajax({ success: function(data) { $persons.html(data).data('ajax-cache', data); }
    }); } else { $persons.html($persons.data('ajax-cache')); //Or read from cache
    }
    Saturday, November 10, 2018 11:11 AM
  • User475983607 posted

    I was actually following this link and believe, this will serve what I expected for custom caching mechanism. Here's the link:

    Custom Caching

    So I tried something like this as follows:

    [WebMethod]
    public static string Concatenate()
    {
       string data = "";
              data += "<table id = 'tblPersons'" +
                      "<thead>" +
                      "<tr class='ui-widget-header'>" +
                      "<th>Name</th>" +
                      "<th>Age</th>" +
                      "</tr>" +
                      "</thead>" +
                      "<tbody>" +
                      "";
                      foreach (var item in GetPersons())
                      {
              data +=   "<tr><td class='val'><span>" + item.name + "</span></td>" +
                        "<td>" + item.age + "</td><br/>" +
                        "<td><button type = 'button' class = 'click' id = 'btnSave'>Click Here</button><td><tr>" +
                        "</td>";
                      }
              data += "" +
                      "</tbody>" +
                      "</table>";
    
        return data;
    }

    So my criteria is if there is no newly added data in the list of object GetPersons(), then the posted data should be retrieved from the cache or if there is anything new, then it'll request from the server. In the front-end, I believe, it should be something like this in short:

    var $persons= $('#lblPersons');

    if ($persons.data('ajax-cache').length == 0) { //If new data, then request from the server $.ajax({ success: function(data) { $persons.html(data).data('ajax-cache', data); }
    }); } else { $persons.html($persons.data('ajax-cache')); //Or read from cache
    }

    I can't determine if you are asking a question, having a problem, or just showing a solution.

    If you are asking for a code review...

    then I suggest rethinking the approach entirely.  I would implement Web API, HTTP GET, and a standard HTTP/Browser caching as illustrated in my previous links.  At the very least, fix the Web Method so that it accepts a parameter and returns data not a string.  Basically, you're serializing twice.  Fix the JavaScript code to append/insert HTML into the DOM.   Use standard System.Web.HttpContext.Current.Cache to cache data by the input parameter.  There's also MemoryCache depending on the design.

    The current design stores duplicate data in the DOM.  This kind of approach leads to complex code because eventually you want or need to sync the data.  The biggest issue, IMO, is the design is all or nothing.  There's no way to cache based on input parameters, a filter, and filtering data is very common.  

    Again, please clarify your post if you need help.

    Saturday, November 10, 2018 1:31 PM