Reputation: 185
I have the following aspx page:
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="index.aspx.cs" Inherits="index" %>
<!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></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Label ID="lblStatus" runat="server" Text="Label">
</asp:Label><asp:Button ID="btnRun" runat="server" Text="Button" onclick="btnRun_Click" />
</div>
</form>
</body>
</html>
The codebehind is:
public partial class index : System.Web.UI.Page
{
protected void btnRun_Click(object sender, EventArgs e)
{
CP CPObj = new CP();
lblStatus.Text = "Starting process..";
CPObj.run();
lblStatus.Text = "Process done.";
}
}
The class needs to do some work (about a minute). When I click the button, the label does not change and only after the class completes the job the label is changed to "Process done.".
I've looked for a solution for a really long time but could not find a clear and straight forward answer.
I've tried to run the class as a thread and got the same result.
public partial class index : System.Web.UI.Page
{
protected void btnRun_Click(object sender, EventArgs e)
{
CP CPObj = new CP();
Thread oThread = new Thread(new ThreadStart(CPObj.run));
lblStatus.Text = "Starting process..";
oThread.Start();
while (!oThread.IsAlive) ;
while (oThread.IsAlive)
{
Thread.Sleep(1000);
}
lblStatus.Text = "Process done.";
}
}
Using JavaScript seems problematic since I already have an onClick call (not sure if I'm correct here).
I'd really appreciate a response.
Thanks! Nadav
Upvotes: 0
Views: 725
Reputation: 88044
Web pages aren't like traditional web forms.
You can't set a label to some value and then within the same callback change that value to something else and have both appear.
What you need to do is use some ajax. The simple way would be to add an update panel and go that route. Basically, you would set the label via javascript to "starting process..." then let the panel change the label once the callback is complete.
Alternatively, you could do it without ajax; but again you set the label via some javascript first. Then let your call back routine over write it.
Upvotes: 1
Reputation: 2138
I think you need to read about page life cycle. Is nice you are updating your label, but since this is web, your data will no go back to the browser until all the code run. So you can't update a label that doesn't exist yet on a page you are not yet sending to the browser ;)
I think JS is the solution for you (not an expert on that field) or maybe some ajax that will query the process runtime, and the process running on another thread?
Upvotes: 0