【问题标题】:Detect if an UpdatePanel is affected by an Update() method call检测 UpdatePanel 是否受 Update() 方法调用的影响
【发布时间】:2015-04-17 15:16:41
【问题描述】:
我在同一页面中使用多个 UpdatePanel,UpdateMode = Conditional,我正在尝试找到一种干净的方法来仅执行与将更新的 UpdatePanel 相关的代码。
所以,当我从 JS 调用 __doPostBack 时,我能够在后面的代码中检测到 UpdatePanel 的名称,该名称要求使用 Request["__EVENTTARGET"] 刷新(这给了我 @更新面板的 987654324@)。
但是当我(从服务器端)调用UpdatePanel1.Update() 方法时,是否有内置方法可以知道更新面板是否即将更新?
【问题讨论】:
标签:
c#
asp.net
asp.net-ajax
【解决方案1】:
我在这里发布给自己我的临时(?)答案。
因为显然无法检测 UpdatePanel 是否正在更新(当 UpdatePanel 被后面的代码更新时),我创建了一个处理更新的类,并将一些数据放入会话,因此,同一个类将能够判断 UpdatePanel 是否正在更新。
所以,我不再直接打电话给UpdatePanel.Update(),而是UpdatePanelManager.RegisterToUpdate()。
bool isUpdating() 方法能够判断 UpdatePanel 是否正在更新,并且可以通过使用 HttpContext.Current.Request["__EVENTTARGET"] 的 Javascript 自动判断 updatePanel 是否正在更新。
注意:isUpdating() 需要在 OnPreRender 页面事件中使用。
public static class UpdatePanelManager
{
private const string SessionName = "UpdatePanelRefresh";
public static void RegisterToUpdate(System.Web.UI.UpdatePanel updatePanel)
{
updatePanel.Update();
if (HttpContext.Current.Session[SessionName] == null)
{
HttpContext.Current.Session[SessionName] = new List<string>();
}
((List<string>)HttpContext.Current.Session[SessionName]).Add(updatePanel.ClientID);
}
public static bool IsUpdating(System.Web.UI.UpdatePanel updatePanel)
{
bool output = false;
// check if there is a JavaScript update request
if (HttpContext.Current.Request["__EVENTTARGET"] == updatePanel.ClientID)
output = true;
// check if there is a code behind update request
if (HttpContext.Current.Session[SessionName] != null
&& ((List<string>)HttpContext.Current.Session[SessionName]).Contains(updatePanel.ClientID))
{
output = true;
((List<string>)HttpContext.Current.Session[SessionName]).Remove(updatePanel.ClientID);
}
return output;
}
public static bool IsUpdatingOrPageLoading(System.Web.UI.UpdatePanel updatePanel, System.Web.UI.Page page)
{
bool output = false;
if (!page.IsPostBack || IsUpdating(updatePanel))
output = true;
return output;
}
}