像我一樣,你會恨規定微軟的答案。 「規定的」答案是使用PageRequestManager來設置請求處理程序。這個請求處理程序(然後)在每個部分回發完成後執行。
請求處理程序實例:
<script id="events" type="text/javascript">
jQuery(document).ready(function() {
// Your normal code goes here
setupSomething();
initializeSomethingElse();
// Setup your partial-postback event handler.
// This is used to rewire all events since all are 'lost' after partial-postback.
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(requestHandler);
});
///<summary>partial postback event handler. Executed after the partial postback is completed. Clears modal popup textboxes</summary>
///<param name="sender"></param>
///<param name="args">http://www.asp.net/ajax/documentation/live/ClientReference/Sys.WebForms/EndRequestEventArgsClass/default.aspx</param>
function requestHandler(sender, args) {
if (args.get_error() == undefined) {
// Your normal code goes here
setupSomething();
initializeSomethingElse();
}
else
alert(args.get_error()); // Do something
}
</script>
這給我們帶來了簡單的答案:
爲什麼不從你的代碼隱藏明確初始化您的用戶控制和保持這種內初始化JavaScript的您的用戶控制HTML(本身)。
void YourUserControl_PreRender(object sender, EventArgs e)
{
try
{
}
catch (Exception ex)
{
}
finally
{
// Do this
ScriptManager.RegisterStartupScript(this.Page, this.Page.GetType(), "registerInitializer", buildInitializer(), true);
}
}
一旦呈現時,「buildInitializer」從邏輯上說,「如果客戶端上存在此功能...調用它。」而且......每次都有效。
private string buildInitializer()
{
StringBuilder javascript = new StringBuilder();
javascript.Append("if (window.initializeMyControl) {");
javascript.Append("if(typeof window.initializeMyControl == 'function') { initializeMyControl(); }");
javascript.Append("}");
return javascript.ToString();
}
現在你的用戶控件初始化可以住在用戶控件應在何處:
<script type="text/javascript">
function initializeMyControl() {
// Your normal code goes here
setupSomething();
initializeSomethingElse();
}
</script>
您正在使用的UpdatePanel? – 2010-09-10 11:10:53
是的主頁面包含許多更新面板 - 包含此用戶控件的面板也包含4個或5個其他面板。 – Dave 2010-09-10 11:14:37
請參閱http://stackoverflow.com/questions/1152946/how-to-have-a-javascript-callback-executed-after-an-update-panel-postback/1153002#1153002 – 2011-03-30 11:40:44