有人問起:裝了 ASP.NET AJAX RC 之後,某些頁面總是在建立 UpdateProgress 時跳腳本錯誤。當初給的答案不太漂亮,後來翻了一下 System.Web.Extensions.dll 的實作,找到一個更乾淨的解法。
實務上很常把統一的「更新中」動畫連同 ScriptManager 一起放在母板頁裡:
<%-- Site.master --%>
<asp:ScriptManager ID="ScriptManager1" runat="server" ScriptMode="Debug" />
<asp:ContentPlaceHolder id="Main" runat="server"></asp:ContentPlaceHolder>
<asp:UpdateProgress ID="UpdateProgress1" runat="server">
<ProgressTemplate>
Hello World!
</ProgressTemplate>
</asp:UpdateProgress>
然後隨便做一個內容頁,放進一個 UpdatePanel:
<%-- Default.aspx --%>
<asp:Content ID="Content1" ContentPlaceHolderID="Main" Runat="Server">
<asp:UpdatePanel runat="server">
<ContentTemplate>
...
</ContentTemplate>
</asp:UpdatePanel>
</asp:Content>
輸出的 HTML 裡會出現這一段:
<script type="text/Javascript">
Sys.Application.initialize();
Sys.Application.add_init(function() {
$create(
Sys.UI._UpdateProgress,
{"associatedUpdatePanelId":null, "displayAfter":500, "dynamicLayout":true},
null, null, $get("ctl00_UpdateProgress1"));
});
</script>
關鍵在於:Sys.UI._UpdateProgress 這個類別是定義在 MicrosoftAjaxWebForms.js 裡的,而這個檔案只有在頁面中實際存在 UpdatePanel 時才會被引入。一旦某個頁面沒有 UpdatePanel,腳本檔沒被載入,那句 $create 卻還是照樣輸出——於是 JavaScript 就炸了。
當時想到的做法是在母板頁硬塞一個 UpdatePanel:
<asp:UpdatePanel runat="server" UpdateMode="Conditional" ID="UP1">
<ContentTemplate></ContentTemplate>
</asp:UpdatePanel>
把 UpdateMode 設為 Conditional,它就永遠不會更新,唯一的作用是「逼」MicrosoftAjaxWebForms.js 被載入。有效,但顯然是權宜之計——多一個無意義的控制項,也多一份維護負擔。
換個角度想:只要讓那句 $create 不出來就好。查過程式碼後發現,這段語句只在 ScriptManager 的 EnablePartialRendering 為 true 時才會產生。既然如此,把這個屬性從母板頁暴露出來即可。
先在 Site.master.cs 裡補一個屬性:
public bool EnablePartialRendering
{
get { return this.ScriptManager1.EnablePartialRendering; }
set { this.ScriptManager1.EnablePartialRendering = value; }
}
接著在不需要局部更新的頁面中於 Init 階段關掉它:
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
(this.Master as Site).EnablePartialRendering = false;
}
這裡有個容易忽略的限制:只有 Init 階段才能設定 EnablePartialRendering,寫在 Page_Load 或之後的時機是不會生效的。
如此一來,該頁既不會輸出多余的 $create,也不必為了 workaround 而在母板頁塞入一個永遠用不到的 UpdatePanel。