Auto Page Refresh in ASP.NET Core MVC

How to Implement Full and Partial Auto Page Refresh in ASP.NET Core MVC:

In this article, I will explain How to Implement Full and Partial Auto Page Refresh in ASP.NET Core MVC Application with an Example. Please read our previous article discussing How to Implement a Dynamic Menu in ASP.NET Core MVC Applications.

What is Auto Page Refresh?

Auto Page Refresh is a technique where a web page is automatically reloaded (or refreshed) at a specified time interval without user interaction. This mechanism ensures that the data presented to the user remains up-to-date, reflecting the latest information from the server without requiring users to refresh their browsers manually.

This approach is commonly employed when data changes frequently, such as in live dashboards, real-time stock markets, or live sports scoreboards. It ensures that users always see the latest content. This can be achieved by refreshing the entire page or updating only a portion via jQuery Ajax.

Real-time Scenarios to Use Auto Page Refresh in Web Applications:

Auto Page Refresh is useful in scenarios where real-time data updates are essential. The following are some of the commonly used cases:

  • Live Score Updates: Sports websites display live scores.
  • Stock Market Dashboards: Financial platforms showing real-time stock prices.
  • Order Management Systems: E-commerce admin panels showing live order statuses.
  • Analytics Dashboards: Pages displaying analytics or metrics that regularly change (e.g., site visitors, orders, or sales).
How to Implement Auto Page Refresh in ASP.NET Core MVC Application

Implementing auto page refresh in an ASP.NET Core MVC application typically combines server-side logic and client-side behavior. There are generally two approaches to implement auto-refresh:

Meta Tag Refresh: You can add a meta tag in the <head> section of your HTML view to automatically refresh the entire page after a specified number of seconds:

<!-- Auto refresh every 10 seconds -->
<meta http-equiv="refresh" content="10">

Using JavaScript with setInterval: You can use JavaScript to refresh the page at intervals:

<script>
  // Reloads the current page every 10,000 milliseconds (10 seconds)
  setInterval(function() {
    window.location.reload();
  }, 10000);
</script>

Using AJAX for Partial Page Refresh: Dynamically call the server (using AJAX/fetch) to retrieve and update data without reloading the entire page. This is for Partial Page Refresh.

For simplicity, many developers use the Meta Tag or JavaScript with the setInterval approach for auto page refresh. If you want more control or a better user experience, you can update just parts of the page via AJAX. In this article, I will show you all these approaches.

Example to Understand Auto Page Refresh in ASP.NET Core MVC:

Let us create a simple ASP.NET Core MVC application demonstrating full and partial page auto-refresh. We will create:

  • A FullRefresh page that automatically reloads the entire page after a set interval (using <meta http-equiv=”refresh” /> or JavaScript).
  • A PartialRefresh page that only updates a portion of the page (using jQuery’s load() method or an AJAX call).
Create a New ASP.NET Core MVC Project
  • Open Visual Studio.
  • Select Create a new project.
  • Choose ASP.NET Core Web App (Model-View-Controller).
  • Name the project (e.g., AutoRefreshDemo) and click Create.
  • Choose the desired .NET version (e.g., .NET 8 or 9), then click Create again.

The default project structure will include folders like Controllers, Models, Views, and wwwroot. We will add our new pages and partial view into these folders.

Create/Update the Home Controller

We need a controller to serve two pages: one for full refresh and one for partial refresh. In the Controllers folder, create or update HomeController.cs with three actions:

  • FullAutoRefresh: Returns a view that reloads the entire page automatically.
  • PartialAutoRefresh: Returns a view that uses AJAX to update a section of the page.
  • GetPartialContent: Returns a PartialView with dynamic content (for example, the current time).

So, please update the HomeController as follows, which is present in the Controllers folder.

using Microsoft.AspNetCore.Mvc;
namespace AutoRefreshDemo.Controllers
{
    public class HomeController : Controller
    {
        // 1) Full Refresh Action
        [HttpGet]
        public IActionResult FullRefresh()
        {
            // For demonstration, pass the current time to the view.
            ViewBag.CurrentTime = DateTime.Now.ToString("hh:mm:ss tt");
            return View(DateTime.Now);
        }

        // 2) Partial Refresh Action
        [HttpGet]
        public IActionResult PartialRefresh()
        {
            // No need to pass current time here; the partial view will be loaded via AJAX.
            return View();
        }

        // 3) Action to return partial content
        [HttpGet]
        public IActionResult GetPartialContent()
        {
            ViewBag.CurrentTime = DateTime.Now.ToString("hh:mm:ss tt");
            return PartialView("_TimePartial");
        }
    }
}
Code Explanation:
  • FullRefresh Action: Returns a view that will fully reload every X seconds. We pass the DateTime.Now object so we can display the current timestamp in the UI. The view will contain client-side JavaScript to reload the entire page.
  • PartialRefresh Action: Returns a view that will partially reload only a specific portion of the page. This view does not need any initial model data. The view will have a section updated via AJAX.
  • GetPartialContent Action: Provides updated data (the current time here) as a partial view of which the client-side AJAX call will load. This action returns a partial view (_TimePartial) containing the current DateTime. It’s designed to be fetched asynchronously so that only this small portion of the page is updated.
Creating the Views:

Let us proceed to create the views:

FullRefresh.cshtml

Create a view file named FullRefresh.cshtml within the Views/Home folder, and then copy and paste the following code:

@{
    // Optional, so we have a minimal layout for demonstration
    Layout = null; 
}

<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title>Full Refresh Demo</title>
    <!-- This meta tag instructs the browser to refresh the page every 5 seconds -->
    <meta http-equiv="refresh" content="5" />

    <!-- Another way to refresh the page every 5 seconds -->
    @* <script>
        // Reload the entire page every 5 seconds (5000 milliseconds)
        setInterval(function() {
            location.reload();
        }, 5000);
    </script> *@
</head>
<body>
    <h2>Full Auto Page Refresh</h2>
    <p>The entire page will refresh automatically every 5 seconds.</p>
    <p>Initial Page Load Time: <strong>@DateTime.Now</strong></p>
    <p>Current Time: <strong>@ViewBag.CurrentTime</strong></p>
</body>
</html>
Code Explanation:

The page displays the current time (passed from the controller) so you can see the refresh visually. When the page reloads, the FullRefresh action hits the controller again, updating the time.

  • Meta Tag: The <meta http-equiv=”refresh” content=”5″ /> instructs the browser to refresh the entire page every 5 seconds.
  • Alternate JavaScript Option: You can also use JavaScript’s setTimeout (or setInterval) to trigger a page reload.
PartialRefresh.cshtml

Create another view file named PartialRefresh.cshtml within the Views/Home folder, and then copy and paste the following code:

@{
    ViewData["Title"] = "Partial Auto Page Refresh";
}

<h2>Partial Auto Page Refresh</h2>
<p>Initial Page Load Time: <strong>@DateTime.Now</strong></p>
<p>Only the content within the "TimeSection" div will refresh every 5 seconds.</p>

<div id="TimeSection">
    <!-- The partial view content will be loaded here -->
    Loading current time...
</div>

<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    // Function to refresh the TimeSection via AJAX
    function refreshTime() {
        $.ajax({
            url: '@Url.Action("GetPartialContent", "Home")',
            success: function (data) {
                $("#TimeSection").html(data);
            },
            error: function () {
                $("#TimeSection").html("Error loading data.");
            }
        });
    }

    // Initial load of the partial view
    refreshTime();

    // Set an interval to refresh every 5 seconds (5000 milliseconds)
    setInterval(refreshTime, 5000);
</script>
Code Explanation:
  • AJAX Call: Using jQuery’s $.ajax method, we call the GetPartialContent action in our controller. This returns the partial view with updated content (current time).
  • Automatic Refresh: The setInterval function calls refreshTime() every 5 seconds, updating only the #TimeSection div instead of the whole page.
  • Partial Update: This ensures a seamless user experience as only the relevant part of the page is updated.
_TimePartial.cshtml

Finally, create a partial view named _TimePartial.cshtml within the Views/Home folder, and then copy and paste the following code:

<div>
    <p>Updated Time: <strong>@ViewBag.CurrentTime</strong></p>
</div>
Code Explanation:
  • This partial view simply displays the current time passed via ViewBag.CurrentTime from the GetPartialContent action.
  • Every AJAX request loads this partial view and injects it into the #TimeSection div on the PartialRefresh page.
Running and Testing the Application

Press F5 (or click the Run button) in Visual Studio to start the application.

FullRefresh Page:

Navigate to /Home/FullRefresh to see the full auto-refresh in action. The entire page will reload every 5 seconds, and you should see the current time update (indicating a complete page refresh).

How to Implement Full and Partial Auto Page Refresh in ASP.NET Core MVC Application

PartialRefresh Page:

Navigate to /Home/PartialRefresh to see the partial auto-refresh. Only the section inside the #TimeSection div is updated every 5 seconds without a full page reload. The rest of the page (e.g., header, navigation) remains static.

How to Implement Auto Page Refresh in ASP.NET Core MVC Application

This application demonstrates two common approaches to auto-refreshing content in ASP.NET Core MVC, each useful in different scenarios depending on whether you need to reload the entire page or update a section. Please click here to see the Real-time use cases of Auto Page Refresh in Web Applications:

When to Use Auto Page Refresh?

You should consider Auto Page Refresh when:

  • Data Changes Frequently: When the underlying data source updates frequently, auto refresh ensures the displayed data reflects the most recent state.
  • User Experience Matters: It improves the user experience by eliminating the need for manual refresh, especially for real-time or near-real-time information.
  • Avoiding Manual Intervention: When you expect users to keep a page open for a long time, auto refresh ensures they have updated content without any effort.

This pattern is useful for dashboards or real-time displays where you want to keep some or all information fresh without forcing the user to refresh the page manually. By combining both techniques, you can see how to reload an entire page (handy in some older or quick solutions) or do more modern partial reloading for a better user experience.

In the next article, I will discuss How to Use Dapper in ASP.NET Core MVC Application with an example. In this article, I explain How to Implement Auto Page Refresh in ASP.NET Core MVC Application with an Example. I hope you enjoy this article, How to Implement Auto Page Refresh in ASP.NET Core MVC Application.

Leave a Reply

Your email address will not be published. Required fields are marked *