locked
How to display live data from REST API? RRS feed

  • Question

  • User-1634202039 posted

    I have REST APIs that return new data every couple minutes. How to display the new data without making the user to the refresh the browser every time?

    AppController.cs

    public IActionResult Index()
    {
        string[] day = {"Mon", "Tue", "Wed", "Thu", "Fri"};
        List<API> results = new List<API>();
        for (var i = 0; i < day.Length; i++)
        {
            var client = new RestClient("https://api.example.com/values/d=" + day[i]);
            var request = new RestRequest(Method.GET);
            request.AddHeader("cache-control", "no-cache");
            request.AddHeader("accept", "application/json; charset=utf-8");
            IRestResponse response = client.Execute(request);
            var responseContent = response.Content;
    
            results.Add(new JavaScriptSerializer().Deserialize<API>(responseContent));
        }
    
        return View(results);
    }

    App.cshtml

    @model Site.Models.API
    
    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    <title>Live data</title>
    </head>
    
    <body>
    <div><h3>Data: <h3></div>
    <div class="APIResult">@Html.DisplayFor(modelItem => result.APIdata);</div>
    </body>
    </html>
    Wednesday, November 6, 2019 7:35 PM

All replies

  • User-474980206 posted

    use the refresh meta tag

    https://en.wikipedia.org/wiki/Meta_refresh

    Wednesday, November 6, 2019 8:23 PM
  • User-1634202039 posted

    So this will also refresh the API in the controller? Like will it display the new data (Since API returns new data every couple minutes).

    Wednesday, November 6, 2019 8:59 PM
  • User-474980206 posted

    its like the user hit refresh. it will reload the html calling the action again.

    Wednesday, November 6, 2019 11:21 PM
  • User1634355159 posted

    Hi iadn,

    Do you want to automatically refresh the page every couple minutes?You could use setTimeout like this in JS:

    @section Scripts {
        <script type="text/javascript"> 
          setTimeout(function(){
           window.location.reload(1);
          }, 120000);
        </script>
    }

    Best Regards,

    Lewis

    Thursday, November 7, 2019 7:27 AM
  • User-1634202039 posted

    Hello Lewis,

    How is this different than refresh meta tag?

    Thursday, November 7, 2019 7:53 PM
  • User-474980206 posted

    its the same, just done with javascript rather than the browser doing it automatically. a javascript timer is more handy when an ajax call will be done, and only a partial screen update done.

    Thursday, November 7, 2019 10:52 PM