正如我所做的那样,您将会讨厌微软规定的答案。 “规定”的答案是使用 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>