解决方案很简单 - 只需IsPostBack
在页面加载后使用 来进行工作,因为当您使用 javascript 触发 UpdatePanel 时,您会将帖子发送回服务器。所以这样做:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// now do your work
}
}
为了使其更高级,您甚至可以简单地检查 PostBack 是否来自该面板。我为此使用了一个检查女巫 UpdatePanel 是否触发事件的函数,所以我们将如下代码:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack && IsUpdatePanelInRendering(Page, upUpdatePanelId))
{
// run the code for update panel 1, me
// ...
}
}
其中 IsUpdatePanelInRendering :
public static bool IsUpdatePanelInRendering(Page page, UpdatePanel panel)
{
Debug.Assert(HttpContext.Current != null, "Where are you called ? HttpContext.Current is null ");
Debug.Assert(HttpContext.Current.Request != null, "Where are you called HttpContext.Current.Request is null ");
// if not post back, let it render
if (false == page.IsPostBack)
{
return true;
}
else
{
try
{
// or else check if need to be update
ScriptManager sm = ScriptManager.GetCurrent(page);
if (sm != null && sm.IsInAsyncPostBack)
{
Debug.Assert(HttpContext.Current.Request.Form != null, "Why forms are null ?");
string smFormValue = HttpContext.Current.Request.Form[sm.UniqueID];
if (!string.IsNullOrEmpty(smFormValue))
{
string[] uIDs = smFormValue.Split("|".ToCharArray());
if (uIDs.Length == 2)
{
if (!uIDs[0].Equals(panel.UniqueID, StringComparison.InvariantCultureIgnoreCase))
{
return false;
}
}
}
}
}
catch (Exception x)
{
Debug.Fail("Ops, what we lost here ?");
}
return true;
}
}