asp.net在运行时更新标签

时间:2017-05-14 17:59:54

标签: javascript asp.net

我理解服务器/客户端的区别......但是随着希望的消亡,我不得不来这里问一个问题。

在我的应用程序中,在某些时候我正在为很多用户生成报告,在那一代报告中,我有标签说%完成。 到目前为止,我已经尝试了代码背面的多个内容

最新的东西

<ListBox x:Name="items" SelectedItem="{Binding SelectedItem}" ItemsSource="{Binding items}" DisplayMemberPath="s"/>
<TextBlock Text="{Binding SelectedItem.s}"/>

创建cookie ......

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

通过我从here获得的答案读取cookie

在此之前,使用

调用javascript
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);

但是到目前为止一切都失败了......任何人都有任何想法,我如何在运行时从代码隐藏中更新该标签? 或者有没有其他任何方式可以实现这一目标?我想在我的asp.net应用程序中创建类似“进度条”或“标签从1到100%增加”的内容,在此报告创建过程中

1 个答案:

答案 0 :(得分:1)

要完成您想要的任务,您需要定期通过ajax调用服务器并要求进度。但这不是一个好的解决方案,因为你不知道打电话的频率。相反,一个更好的解决方案,如果你可以告诉服务器&#34;他们做这项工作并向我报告进展情况,那将是理想的选择。在这种情况下,服务器需要向浏览器发送消息,您最好的朋友是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();
    });
    
  7. 以下是该页面的完整代码。

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

    确保遵循所有步骤。如果省略任何步骤,则无效。不要只是复制粘贴代码(虽然它已经过测试),但试着理解它,所以如果你需要维护它,你就知道发生了什么。