Cheshie
Cheshie

Reputation: 2837

Change labels text with javascript and read it from code behind

I have an asp.net page with a label on it. The label has no text.

<asp:Label ID="Label1" runat="server"></asp:Label>

At some point, I call a javascript function that adds some content to the label, as follows:

function myFunc() { 
                label = document.getElementById("Label1");
                list = document.getElementById("list");
                label.innerHTML = list.innerText;
            }

After that function is done, I click a button on the page, that calls its onclick event:

protected void Button1_Click(object sender, EventArgs e)
    {
        string a = Label1.Text;
    }

For some reason, the Label1.Text is still empty. Why? Is there any way I could fix this?

Thanks.

Upvotes: 0

Views: 2650

Answers (2)

David
David

Reputation: 218808

Because the value doesn't get posted to the code-behind.

No matter how much WebForms tries to hide this, the only data that gets posted from a web page to the server is data that's in form elements. What WebForms does with things like label texts is stuff them into an input type="hidden" as one big serialized base-64 encoded string. (It calls this "view state" but it's really just a hidden form element.)

Changing the page markup doesn't change anything server-side because page markup isn't posted to the server.

What you can do is create a form element and change that along with the markup. Something as simple as:

<asp:HiddenField runat="server" ID="Hidden1" />

Whenever you change the markup in JavaScript, also change that value:

label = document.getElementById("Label1");
hidden = document.getElementById("Hidden1");
list = document.getElementById("list");
label.innerHTML = list.innerText;
hidden.value = list.innerText;

This will be posted back to the server, since it's a form element. Then you can access the value server-side:

string a = Hidden1.Value;

Upvotes: 2

Sandip Bantawa
Sandip Bantawa

Reputation: 2880

ID="Label1" for ASP.NET is server side, but for javascript we need a client side ID ie "<%=Label1.ClientID%>"

Upvotes: 0

Related Questions