Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 618
Riain McAtamney Avatar asked Jun 01 '10 11:06

Riain McAtamney


3 Answers

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.

like image 174
Riain McAtamney Avatar answered Nov 07 '22 06:11

Riain McAtamney


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" />
like image 45
Daniel Dyson Avatar answered Nov 07 '22 05:11

Daniel Dyson


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.

like image 2
Ivan Zlatanov Avatar answered Nov 07 '22 06:11

Ivan Zlatanov