asp.net 用户控件内的更新面板重新加载整个控件

asp.net updatepanel inside usercontrol reload the whole control

我想创建一个表示进度条的用户控件。

ASCX:

<%@ Control Language="C#" AutoEventWireup="true" CodeBehind="ProgressBar.ascx.cs" Inherits="A2Controls.Controls.ProgressBar" %>

<div class="progress">
    <div class="progress-bar" role="progressbar" aria-valuenow="<%# this.Value %>" aria-valuemin="0" aria-valuemax="100" style="width: <%# this.Value %>%">
        <span class="sr-only"><%# this.Value %> Complete</span>
    </div>
</div>

隐藏代码:

public partial class ProgressBar : System.Web.UI.UserControl
{
    public int Value { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

ASPX:

<asp:UpdatePanel runat="server">
    <ContentTemplate>
        <asp:Timer runat="server" ID="clock" OnTick="clock_Tick" Interval="1000" Enabled="true"></asp:Timer>
        <uc1:ProgressBar runat="server" ID="ProgressBar" />
    </ContentTemplate>
    <Triggers  >
        <asp:AsyncPostBackTrigger ControlID="clock" EventName="Tick" />
    </Triggers>
</asp:UpdatePanel>

隐藏代码:

protected void clock_Tick(object sender, EventArgs e)
{
    this.ProgressBar.Value++;
}

问题是每次调用 tick 函数时,updatepanel 都会刷新并重新加载整个用户控件(我的意思是调用构造函数)!我试过将 updatepanel 逻辑放在用户控件中,但没有区别。

如何防止用户控件再次重新实例化?

您必须将 Value 属性 更改为:

public int Value
{
    get
    {
        if (ViewState["Value"] != null)
            return (int)ViewState["Value"];
        else
            return 0;
    }
    set
    {
        ViewState["Value"] = value;
    }
}

通过这种方式,您可以在回传中保持 属性 的值。

HTTP 是无状态协议。不幸的是,您必须像 ViewState 那样使用某种技巧来跨请求持久保存数据。你最好看看here and here,深刻体会到这里没有错