Veljko89
Veljko89

Reputation: 1953

asp.net update label in runtime

I understand server / client side difference ... but as hope dies last, I had to come here and ask a question.

In my app, at some point I am generating report for lots of users, during that generation of report, I have label that says % complete. So far I have tried multiple stuff in my back side of code

Newest thing

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("~/Klijenti/Klijenti.aspx");
request.Headers.Add("ReportPercentage", Value.ToString());

Creating cookie ...

var myCookiePerc = Response.Cookies["ReportPercentage"];

if (string.IsNullOrWhiteSpace(myCookiePerc.Value) || 
    string.IsNullOrEmpty(myCookiePerc.Value))
{
     myCookiePerc = new HttpCookie("ReportPercentage");               
}

Response.Cookies.Remove("ReportPercentage");

myCookiePerc.Values["ReportPercentage"] = Value.ToString();
myCookiePerc.Expires = DateTime.UtcNow.AddMinutes(2);
Response.Cookies.Add(myCookiePerc);

And reading cookie by answer I got from here

And before that, calling javascript with

ClientScript.RegisterStartupScript(GetType(), "nyScript", "updateCompletePercent(" + percent + ", true);
ScriptManager.RegisterStartupScript(GetType(), "nyScript", "updateCompletePercent(" + percent + ", true);

But as everything failed so far ... Anyone got any idea, how I can update that label from codebehind, during runtime? Or does anyone have any other way how this can be accomplished? I just want to have something like "Progress bar" or "label increasing from 1 to 100%" in my asp.net app, during this report creation

Upvotes: 0

Views: 679

Answers (1)

CodingYoshi
CodingYoshi

Reputation: 26989

To accomplish what you want, you need to periodically call the server via ajax and ask for progress. But that is not a good solution because you cannot know how often to call. Instead, a better solution, it would be ideal if you can tell the server "hey do this work and report progress to me". And in a situation like this where the server needs to send messages to the browser, your best friend is SignalR.

Follow the steps below to accomplish this task:

  1. Download the the SignalR NuGet Package
  2. Add this line of code to ConfigureAuth method of Startup class:

    app.MapSignalR();
    
  3. Add a web method to your code behind which will do the work. For this example you can use this method:

    public partial class _Default : Page
    {
        // We are mimicking some work here
        [WebMethod]
        [ScriptMethod(ResponseFormat = ResponseFormat.Json)]
        public static string LongRunningProcess()
        {
            int itemsCount = 100;
    
            for (int i = 0; i <= itemsCount; i++)
            {
                Thread.Sleep(500);
                Messenger.SendProgress("Process in progress...", i, itemsCount);
            }
    
            return "Completed";
        }
    }
    
  4. Add this class (Make sure to import using Microsoft.AspNet.SignalR;:

    // We must have this class in order for SignalR to communicate between server and client.
    // We don't have to define any method here because in this example we want to send data directly from server. 
    // In a chat application it will take a message from a client and send it to other client(s) etc...
    public class ProgressHub : Hub
    {
    
    }  
    
  5. Add this class to send messages to client:

    public class Messenger
    {
        public static void SendProgress(string progressMessage, int progressCount, int totalItems)
        {
            // In order to invoke SignalR, let's get the context 
            var hubContext = GlobalHost.ConnectionManager.GetHubContext<ProgressHub>();
    
            // Calculate %
            var percentage = (progressCount * 100) / totalItems;
    
            // Send to client
            hubContext.Clients.All.AddProgress(progressMessage, percentage + "%");
        }
    }
    
  6. You need some javascript to listen to messages coming from the server.

    $(function () {
    
        // Reference the auto-generated proxy for the hub.
        var progress = $.connection.progressHub;
        console.log(progress);
    
        // Create a function that the hub can call back to display messages.
        progress.client.addProgress = function (message, percentage) {
    
            // we got a message from the server so update the label
            $('#<%=Label1.ClientID%>').html(percentage);
        };
    
        //Before doing anything with our hub we must start it
        $.connection.hub.start();
    });
    

Here is the complete code for the page.

    <%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Asp._Default" %>

    <asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">

    <!-- This is what will do the magic -->
    <script src="Scripts/jquery.signalR-2.2.2.min.js"></script>
    <script src="signalr/hubs"></script>

    <!-- We will udpate this label. -->
    <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>

    <!-- We will start the process when this button is clicked. -->
    <button onclick="StartProcess()" type="button">Start the process</button>

    <script>
        // Let's call the server using jQuery AJAX
        function StartProcess() {
            $.ajax({
                type: "POST",
                url: "Default.aspx/LongRunningProcess",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    alert(data.d);
                }
            });
        }

        $(function () {

            // Reference the auto-generated proxy for the hub.
            var progress = $.connection.progressHub;
            console.log(progress);

            // Create a function that the hub can call back to display messages.
            progress.client.addProgress = function (message, percentage) {

                // we got a message from the server so update the label
                $('#<%=Label1.ClientID%>').html(percentage);
            };

            //Before doing anything with our hub we must start it
            $.connection.hub.start();
        });

    </script>
    </asp:Content>

Make sure you follow all the steps. If you omit any of the steps, it will not work. Do not just copy paste the code (although it has been tested) but try to understand it so if you need to maintain it, you know what is going on.

Upvotes: 1

Related Questions