简体   繁体   中英

Updating ASP.NET label while processing

I have a method thats run on a button click, with 4 labels. What I need to do is update a label after each block of code executes. I've tried threading, updatepanels, etc and can't seem to get anything to work. I thought the timer would work, but it only ticks when you're not inside a method. The code looks something like this:

private void SomeMethod()
{
     label1.text = "Processing...";
     AnotherMethod();
     label1.text = "Done.";
     label2.text = "Processing...";
     AnotherAnotherMethod();
     label2.text = "Done.";

     //etc...
}

You have a misunderstanding of how asp.net works. Your server code runs in response to a request from a browser for a complete html page. This is true even when all you really want to do is run some button click code. The entire page must be rebuilt from scratch anyway, even on postbacks. It's just the way web forms are designed.

As soon as the page is rendered to the browser, that instance of your page class is destroyed . On the next postback you'll start from scratch again, with the notable exceptions of the session, viewstate, and the application cache. Even the page's previous DOM instance in the browser is replaced.

So when you set the text property of the label you aren't directly updating anything visually in the browser. All you are doing is updating some temporary storage in your page class. As the last stage of executing your server code, all those temporary variables are used to render the completed html and the response is finally sent to the browser and shown to the user.

That should be enough information to give you an understanding of why your code doesn't behave as expected. It's running all of the code in the method before any of your property changes make their way to the browser. Therefore, the only thing the user sees is the final state of the operation.

Now ajax can complicate things a bit. When using an ajax control you might not be updating the entire page anymore, but the concept still applies: one request is made, and one response is received and used to update the entire context of the request. You can further muddle things if you have a lot of javascript in place to handle the result of the ajax request.

Unfortunately, there's no quick fix for the code you posted. You'll need to think about how this really works and decide how you want your page to flow.

您是否可以将3种方法公开给客户端脚本,然后从客户端代码依次调用它们,当method1完成时,客户端脚本将更新ui,然后调用method2,依此类推...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM