Riain McAtamney
Riain McAtamney

Reputation: 6432

Updating label using jquery and code behind

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

Upvotes: 6

Views: 4398

Answers (4)

Daniel Dyson
Daniel Dyson

Reputation: 13230

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" />

Upvotes: 2

Riain McAtamney
Riain McAtamney

Reputation: 6432

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.

Upvotes: 3

Ivan Zlatanov
Ivan Zlatanov

Reputation: 5226

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.

Upvotes: 2

Hogan
Hogan

Reputation: 70523

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.

Upvotes: 0

Related Questions