views:

476

answers:

2

Hello, I use ASP.NET and have a label control on my page, which I fill with the jQuery-Command

$('#<%= myLabel.ClientID %>').html(content);

.val() does not seem to work with this.

Somehow, I have Problems getting the content in code-behind. In the code, the myLabel.Text-Property is still empty.

+1  A: 

I think your problem is that labels (rendered as span tags) are inherently read-only in the asp.net world. They're not meant to be used as 'input' controls, and as such changes to their HTML on the client-side are ignored on the server-side, where values are set based on ViewState.

To do what you are asking, you'd have to notify the server of the change as well, such as by using AJAX. The only issue here is ajax webmethods in your code behind are static, and because of this can't access the page's control set to change the .Text value.

In the end the easiest option is to make use of hidden fields as Nick said. These are technically 'input' controls and their values changed on the client-side are sent to the server as you desire. You'd just have to keep the label/span and hidden field/input synchronized on the client.

Hope this helps.

KP
+2  A: 

If you want to display the value on the client and have it available on the page, you need an input that'll get sent to the code-behind when you POST like this:

$('#<%= myLabel.ClientID %>').html(content);
$('#<%= myInput.ClientID %>').val(content);

<asp:Label Id="myLabel" runat="server" />
<asp:HiddenField ID="myInput" runat="server" />

In the code-behind:

myInput.Value
Nick Craver
+1. `HiddenField` controls are definitely the simplest solution to this problem.
KP
This is really the simplest method, I have used it.
Jan-Frederik Carl