方法运行时更新标签文本

时间:2009-06-11 07:55:47

标签: c# asp.net user-interface

目前,发展更是一种爱好;如果这是一个基本问题,请道歉,虽然在网上搜索几个小时后我似乎无法找到答案。我目前正在为我的团队构建一个支持工具,该工具运行了许多SQL查询和BCP处理并返回结果。其中一些操作需要一段时间,我想用状态消息更新Web UI。以前我一直在使用Label1.Text = text;

但是现在我想在我的方法运行时多次更新Label1.text。尽可能尝试,但它只显示方法中的最后一次更新。

我编写了一个小测试来尝试深入研究: -

网页

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Template._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>


</head>
<body>
<form id="form1" runat="server">
<div>
    <asp:Label ID="progress" runat="server" Text=""></asp:Label><br />
    <asp:Image ID="Image1" runat="server" ImageUrl="~/Image/loader.gif" 
        Visible="False" />
</div>
</form>
</body>
</html>

C#CodeBehind

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace Template
{
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        uiUpdate("OUT", 1);           
        wait();
        uiUpdate("In", 0);
    }

    protected void uiUpdate(string text, Int32 image)
    {                      
        if (image == 1)
        {
            Image1.Visible = true;                                             
        }
        else
        {
            Image1.Visible = false;
        }
        progress.Text = text;

    }

    protected void wait()
    {
        DateTime wait;
        wait = DateTime.Now + TimeSpan.FromSeconds(10);
        while (wait > DateTime.Now)
        {
        }
    }

有没有办法让Label1&amp;要在Page_load运行时更新图像吗?

或者我是以完全错误的方式看待这种情况(毫无疑问!)

由于

2 个答案:

答案 0 :(得分:2)

HTML作为整页请求并不是最简单的:

  • 您的浏览器向服务器发送请求(包括所有表单变量,Cookie等)
  • 服务器进行一些处理并发送响应(通常为html)
  • 您的浏览器处理响应并呈现显示

所有更新都发生在中间的子弹中,所以没有:没有办法让浏览器更新:您的代码在服务器上执行,没有与客户端对话

如果您需要这种类型的行为,您将不得不查看AJAX工具 - 在每个步骤执行“足够”工作以进入下一个里程碑并更新标题...使用常规ASP.NET {{3可能有趣;对于MVC或其他(非ASP.NET)设置,jQuery将是你的朋友。不幸的是,这不是一个微不足道的话题。

答案 1 :(得分:1)

如果我理解你的问题是正确的,你不能在常规的asp.net中这样做,你需要使用ajax,并制作一个ajax方法,然后在运行时更新标签的文本。您可以使用ajax MS scriptmanager来执行此操作。 如果不是为了高性能,你可以使用update panel,否则你应该自己使用脚本管理器。

相关问题