views:

231

answers:

4

Hi,

I have a label on a page and I'm updating the text property of the label (with a calculated value) when text is changed in a textbox.

I'm updating the label like so:

$myLabel.text("123");

The text is being displayed correctly on the screen butwhen I try to save the text value to an object in the code behind (When I press a button) the text property of the label is "" and not "123".

Code behind:

var myLabel = myLabel.Text;
//the var myLabel is "" when it should be "123"

Any ideas as to why this would be?

Thanks in advance,

Zaps

+1  A: 

Why don't you check the value that was entered in the textbox. based on your description, that should be the same and it will be available. Otherwise, I think you need to post some more code to clarify what you are doing.

The value of the label text needs to be stored in ViewState, otherwise it will be overwritten on the postback triggered by the button click.

One option would be to also change the value of a hidden control. Any changes to this value will be available in the code behind on postback.

<asp:Hidden id="hiddenLabel" runat="server" />
Daniel Dyson
Because the are calculations done on the value in the textbox in javascript. This means the label text isn't whats in the textbox.
Zaps
Ok, you should make that clearer in your question. "Hello" doesn't appear to be a calculated value.
Daniel Dyson
apologies, I have updated the question. You are right "hello" was a bad example. Thanks
Zaps
No worries. I have updated my answer with one suggestion that you could try.
Daniel Dyson
A: 

In what function are you putting var myLabel = myLabel.Text;?

It won't work in the init function -- you need to give the page time to load from the viewstate. Best in the button push event handler.

Update:

You need to use an form input control (eg TextBox) not label. Labels are readonly.

Hogan
it's on the button_click event
Zaps
+1  A: 

Html controls like labels, spans, divs don't post their values to the server - while inputs do. ASP.NET maintains changes in controls by using ViewState.

When you change the value of a server control, it's state is often persisted there. If you change the value on the client side via JavaScript, the ViewState isn't changed, and this is why on PostBack you get the original Empty value.

Ivan Zlatanov
A: 

Not sure if this is the correct way to do it but I got around the problem by using a hidden field.

I updated the label text as above:

$myLabel.text("hello");

but then I updated the hidden field value:

$('#<%= hiddenField.ClientID %>').val("hello");

I was then able to use the hidden field in the code behind:

var myLabel = hiddenField.Value.ToString();

This seems to work fine.

Zaps