如何从回调函数在代码后面更新标签

本文关键字:更新 标签 代码 回调 函数 | 更新日期: 2023-09-27 17:54:11

我的ASP。. NET项目调用REST-Client库函数,该回调函数应该调整标签。但是asp标签在callback被调用后不会改变或更新。可以通过回调吗?

default . aspx:

<asp:UpdatePanel runat="server" id="UpdatePanel1">
    <ContentTemplate>
        <asp:Button OnClick="connect" Text="Connect" runat="server" />
        <asp:Label runat="server" Text="Label to be changed" id="Label1">
        </asp:Label>
    </ContentTemplate>
</asp:UpdatePanel>

Default.aspx.cs:

public void connect(object sender, EventArgs e)
{
    Program restCLient = new Program();
    restCLient.startConnection(writeToConsole);
}
public void writeToConsole(string str)
{
    Label1.Text = str;
}

Programm.cs:

public void startConnection(Action<string> callbackLog)
{
    callbackLog("result");
}

如何从回调函数在代码后面更新标签

Label1在startConnection中没有被引用,它将有一个新的实例。最好的方法是从startConnection返回一个字符串,并在connect()方法中更改标签。

一种解决方法是将调用页实例作为参数发送给startConnection方法,并调用该参数上的方法。假设您的页面类名为Default,并且program .cs位于同一应用程序中,您可以使用如下命令:
public void startConnection(ref Default callingPage)
{
    callingPage.writeToConsole("result");
}

然后你会像这样调用这个方法:

restCLient.startConnection(this);