【问题标题】:Why is my user control not instanciated on a postback?为什么我的用户控件没有在回发时实例化?
【发布时间】:2010-04-30 00:19:17
【问题描述】:

我想将 UpdatePanel 的触发器设置为同一页面上 UpdatePanel 之外的用户控件。用户控件是在设计时添加的,而不是在运行时添加的。
如果我静态声明触发器,则会收到错误“在 UpdatePanel 中找不到触发器的 ID 为 'xx' 的控件”。我尝试在运行时在 Page_Init 或 Page_Load 中添加触发器,但它失败了,用户控件为空,尽管它启用了 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为空)。

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

编辑: 用户控件未实例化,因为它已被缓存。事实上,让用户控件既被缓存又能够处理事件似乎是不可能的。我一定错过了什么,因为这对我来说似乎很糟糕。
如果有人知道我做错了什么,请告诉。

【问题讨论】:

    标签: asp.net updatepanel user-controls


    【解决方案1】:

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

    【讨论】:

    • 用户控件包含一个不会改变的大下拉列表(5K 元素),因此是缓存。但是当用户选择一个项目时,必须触发一些查询来更新一些其他字段(在提到的 UpdatePanel 中的那些)。有错吗?
    【解决方案2】:

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

    ScriptManager1.RegisterAsyncPostBackControl(CustomComponentDropDown);

    也不应该

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

    只是

    trigger.ControlID = CustomComponentDropDown.ID;
    

    【讨论】:

    • 这并没有带回CustomComponentDropDown,在第一个PostBack的Page_Load时它仍然为空。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多