如何通过代码隐藏的回调函数更新标签?

How to update label from callback function in code behind?

我的 ASP.NET 项目调用了一个 REST-Client 库函数,该回调应该调整标签。但是 asp 标签在调用回调后不会更改或更新。是否有可能过度回调?

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 中引用,它将有一个新实例。最好的方法是 return 来自 startConnection 的字符串并更改 connect() 方法中的标签。

一种解决方法是将调用页面实例作为参数发送到 startConnection 方法,然后根据该参数调用该方法。假设您的页面 class 被称为 Default 并且 Programm.cs 在同一个应用程序中,您可以使用这样的东西:

public void startConnection(ref Default callingPage)
{
    callingPage.writeToConsole("result");
}

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

restCLient.startConnection(this);