解決方案很簡單 - 只需使用IsPostBack
即可在加載頁面後進行工作,因爲當您使用JavaScript觸發UpdatePanel時,您會發送一條帖子回到服務器。所以這樣做:
protected void Page_Load(object sender, EventArgs e)
{
if (IsPostBack)
{
// now do your work
}
}
爲了使它更先進,你甚至可以簡單地檢查回發是否來自該面板。我使用該查收女巫的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;
}
}
謝謝!我現在就試試這個...... – CodingIsSwell
我仍然無法讓它表現正確,Aristos。 我希望整個頁面被渲染和可見,包括一些用戶控件等。然後,我想要一個特定的更新面板(其中只有一個用戶控件)加載並完成其所有工作之後的其他部分該頁面在那裏。 此外,在我的情況下,主頁面做了一些工作,並將一些數據保存在會話變量中。然後,我希望延遲更新面板/用戶控件使用它來做更多的工作。 – CodingIsSwell
如何告訴我的用戶控件在第一次加載頁面時不會觸發,而只是稍後通過javascript updatepanel調用異步執行其工作? – CodingIsSwell