Search code examples
c#asp.netupdatepanel

Assigned text to label doesn't get updated


So this is my function which serves an AJAX call:

public void Button1_Click(object sender, EventArgs e)
        {
            Button1.Text = "surprise";
            Label1.Text = "surprise!!";
            Label2.Text = "surprise!!";
        }

This is the aspx. Scriptmanager is set.

    <p>Síðast slóstu inn:
        <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
        <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
    </p>
    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <asp:TextBox ID="TextBox1" runat="server">asd</asp:TextBox>
            <asp:TextBox ID="TextBox2" runat="server">dsa</asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>

You can see for yourselves if you want: http://webapplication44730.azurewebsites.net/data

As you can see, the button text changes to "surprise" but the labels, Label1 and Label2 which should appear after 'inn,' don't.


Solution

  • The cause it that those labels are not inside the UpdatePanel, which means they will not get updated from the AJAX callback.

    Set the update panel around every control you need to update:

    <asp:UpdatePanel ID="UpdatePanel1" runat="server">
        <ContentTemplate>
            <p>Síðast slóstu inn:
                <asp:Label ID="Label1" runat="server" Text=""></asp:Label>
                <asp:Label ID="Label2" runat="server" Text=""></asp:Label>
            </p>
            <asp:TextBox ID="TextBox1" runat="server">asd</asp:TextBox>
            <asp:TextBox ID="TextBox2" runat="server">dsa</asp:TextBox>
            <asp:Button ID="Button1" runat="server" Text="Save" OnClick="Button1_Click" />
        </ContentTemplate>
    </asp:UpdatePanel>