Does anyone has a idea why?
Short Answer
The string text = Label1.Text;
statement runs on the server-side. The DisplayTime()
function runs on the client-side. Since the server-side code runs before the client-side code does, the server does not know what changes DisplayTime()
is going to make. You will need to send the changes back to the server.
Further Explanation
In ASP.NET web pages, the server-side (server) and the client-side (client) communicate through HTTP. The client is usually a web browser.
- The client sends a request to the server.
- In response, ASP.NET code on the server goes through the page life cycle to generate an HTML page.
- The server sends that page via HTTP back to the client.
- The client renders the HTML and optionally changes it with JavaScript.
When your code calls RegisterStartupScript
, the HTML page is still on the server (step 2). Importantly, the client hasn't invoked the DislayTime()
function yet!
When your code calls string text = Label1.Text;
, the HTML page is still on the server-side too. Again, the client hasn't invoked the DisplayTime()
function. Result: Label1
will have its original value.
// DisplayTime() only goes live once it reaches the client.
Page.ClientScript.RegisterStartupScript(
GetType(), "DisplayTime", "DisplayTime();", true);
// The client-side hasn't called `DisplayTime()` yet.
string text = Label1.Text;
Possible Options
If we want the server-side to be aware of the JavaScript manipulations (or any other client-side changes), then we must use HTTP to send those changes back to the server. This can be a POST or another HTTP verb. You can POST back the whole page or you can use AJAX. That's probably beyond the scope of this answer.