2017-05-14 83 views
0

我理解服務器/客戶端的差異......但是,隨着希望最後消亡,我不得不來到這裏問一個問題。asp.net在運行時更新標籤

在我的應用程序中,在某個時間點,我爲很多用戶生成報告,在生成報告期間,我有標記說%完成。 到目前爲止,我已經嘗試了多種東西在我的代碼

最新的東西

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

創建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); 

而到答案閱讀餅乾我從here

在此之前,調用JavaScript與

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

但是到目前爲止一切都失敗了......任何人都有任何想法,我如何在運行時期間從代碼隱藏更新該標籤? 還有沒有人有任何其他方式如何可以完成?我只想在我的asp.net應用程序中創建一個類似於「進度條」或「標籤從1增加到100%」的內容

+0

你將無法完成 – hardkoded

+0

@kblok這是可能的。看到我的答案。 – CodingYoshi

+0

@CodingYoshi當然,生活中一切皆有可能,但他必須重新實現他的整個代碼。 – hardkoded

回答

1

要完成您想要的任務,您需要通過定期調用服務器阿賈克斯並要求進步。但這不是一個好的解決方案,因爲你不知道多久打一次電話。相反,更好的解決方案,如果你能告訴服務器「嘿,做這項工作並向我報告進展」,這將是理想的。在這種情況下,服務器需要向瀏覽器發送消息,您最好的朋友是SignalR

按照下面的步驟來完成此任務:

  1. 下載的SignalR NuGet Package
  2. 這行代碼添加到ConfigureAuth方法Startup類:

    app.MapSignalR(); 
    
  3. 添加Web方法到您的代碼後面將完成工作。在這個例子中,你可以使用這個方法:

    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. 加入這個類(確保導入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. 添加這個類將消息發送到客戶端:

    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. 您需要一些javascript來收聽來自服務器的消息。

    $(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(); 
    }); 
    

下面是頁面的完整代碼。

<%@ 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> 

請務必遵循的所有步驟。如果你省略了任何步驟,它將不起作用。不要只是複製粘貼代碼(雖然它已經過測試),但試着理解它,所以如果你需要維護它,你就知道發生了什麼。

+0

非常感謝你的解釋 – Veljko89