Let’s say you want to display a progress bar on a page that shows the progress of a loop that acts on records in a database. You write in C# and this is Asp.net MVC Core application.

First you have to install nuget packet Microsoft.AspNetCore.SignalR.

Then in the Program.cs code file add this lines of code:

 builder.Services.AddSignalR();
 app.MapHub<ProgressHub>("/progressHub");

Next step to do is add a class ProgressHub.cs in your Namespace

using Microsoft.AspNetCore.SignalR;
  
public class ProgressHub : Hub
{

}

And now in your controller code where you do operations on database you write something like this:

 private readonly IHubContext<ProgressHub> _hubContext;

 public SettingsController(IHubContext<ProgressHub> hubContext) 
 { 
     _hubContext = hubContext; 
 }

public async Task<IActionResult> Action1()
{

            var records = MethodGetRecords().ToList();

            int totalRecords = records.Count(); 
            int processedRecords = 0;

            foreach (var record in records)
            {
                processedRecords++;
                var progress = (processedRecords * 100) / totalRecords;
                await _hubContext.Clients.All.SendAsync("UpdateProgress",progress);
            }
 
    return Ok("");
}

And in view you must include java library from Microsoft and then you can display progress in progress bar

@section Scripts
{
    <script type="text/javascript">
        $(function () {
            var connection = new signalR.HubConnectionBuilder().withUrl("/progressHub").build();

            connection.on("UpdateProgress", function (progress) {
                $("#progress").css("width", progress + "%");
            });

            connection.start().catch(function (err) {
                return console.error(err.toString());
            });
        });
  
    </script>
}

   <form asp-action="Action1" asp-controller="Settings" method="post" enctype="multipart/form-data">   
       <button type="submit">Action1</button> 
   </form>

   <div id="progress-bar" style="width: 100%; background-color: #f3f3f3;" class="form-control">
       <div id="progress" style="width: 0%; height: 30px; background-color: #4caf50;"></div>
   </div>

And this is everything you need to get this working !!!

Podobne wpisy

Dodaj komentarz

Twój adres e-mail nie zostanie opublikowany. Wymagane pola są oznaczone *