为什么我的用户控件没有在回发上实例化?

时间:2010-04-29 14:43:33

标签: asp.net updatepanel user-controls

我想将UpdatePanel的触发器设置为同一页面上UpdatePanel外的用户控件。用户控件是在设计时添加的,而不是在运行时添加的 如果我静态声明触发器,则会收到错误“找不到UpdatePanel中触发器的ID为xx的控件”。我尝试在Page_Init或Page_Load中在运行时添加触发器,但它失败,用户控件为null,尽管它启用了ViewState。有人知道如何解决这个问题吗?

以下是用户控件的代码:

<%@ Control Language="C#" AutoEventWireup="true" CodeFile="ComponentDropDownControl.ascx.cs" Inherits="ComponentDropDownControl" EnableViewState="true" %>
<asp:DropDownList ID="ComponentDropDown" runat="server" DataSourceID="ComponentFile"
DataTextField="name" DataValueField="name" OnSelectedIndexChanged="ComponentDropDown_SelectedIndexChanged" AutoPostBack="True" EnableTheming="True">
</asp:DropDownList><asp:XmlDataSource ID="ComponentFile" runat="server" DataFile="~/App_Data/Components.xml" XPath="//component"></asp:XmlDataSource>

这是在aspx页面中:

<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="create.aspx.cs" Inherits="create" Title="Create task" %>

<%@ Register Src="ComponentDropDownControl.ascx" TagName="ComponentDropDownControl"
TagPrefix="uc1" %>
...
<uc1:ComponentDropDownControl ID="CustomComponentDropDown" runat="server" EnableViewState="true" />

在aspx页面的Page_Load函数中,以下行在第一次工作,但在第一个PostBack上失败(第2行,CustomComponentDropDown为null)。

AsyncPostBackTrigger trigger = new AsyncPostBackTrigger();
trigger.ControlID = CustomComponentDropDown.UniqueID.ToString();
UpdatePanel1.Triggers.Add(trigger);

编辑:用户控件未实例化,因为它已缓存。事实上,似乎不可能让用户控件既缓存又能够处理事件。我必须遗漏一些东西,因为这对我来说似乎很糟糕 如果有人知道我说错了什么,请告诉你。

2 个答案:

答案 0 :(得分:0)

您希望在什么情况下处理事件并缓存控件?我看到处理事件的唯一原因是要么改变内部状态,要么改变显示状态。在任何一种情况下,缓存都将消除这种可能性。

答案 1 :(得分:0)

您是否将Control注册为异步回发控件?

ScriptManager1.RegisterAsyncPostBackControl(CustomComponentDropDown);

另外,不应该

trigger.ControlID = CustomComponentDropDown.UniqueID.ToString();

只需

trigger.ControlID = CustomComponentDropDown.ID;