假如你像我一样,无法抵挡这种诱惑,一个页面上放很多个UpdatePanel以及沉溺于Ajax的好处之中。UpdatePanel对于每个人来说都是很容易实现的,它不需要UpdatePanel在后台是怎么操作的。
但是,UpdatePanel在客户端和服务器之间交互的透明缺乏成为你的绊脚石。让我们来看下面这个例子:
<asp:ScriptManager ID="ScriptManager1" runat="server" /> <asp:UpdatePanel runat="server" ID="up1"> <ContentTemplate> <asp:Label runat="server" ID="Label1" Text="Update Me!" /><br /> <asp:Button runat="server" ID="Button1" Text="Postback Update" OnClick="Button1_Click" /> </ContentTemplate> </asp:UpdatePanel>
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = DateTime.Now.ToLongDateString();
}
这个例子简单但足够说明问题了,button1点击之后将异步传回数据,让我们来看看发生了什么:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" /> <script language="javascript"> function UpdateTime() { PageMethods.GetCurrentDate(OnSucceeded, OnFailed); } function OnSucceeded(result, userContext, methodName) { $get('Label1').innerHTML = result; } function OnFailed(error, userContext, methodName) { $get('Label1').innerHTML = "An error occured."; } </script> <asp:Label runat="server" ID="Label1" Text="Update Me!" /><br /> <input type="button" id="Button2" value="Web Method Update" onclick="UpdateTime();" />
[WebMethod]
public static string GetCurrentDate()
{
return DateTime.Now.ToLongDateString();
}
Through this method, we’ve completely eliminated the HTTP POST data that was present
in the UpdatePanel’s request,
and reduced the response down to just the data we’re interested in requesting:
Using JSON, the entire HTTP round trip is 24 bytes, as compared to 872 bytes
for the UpdatePanel.
That’s roughly a 4,000% improvement, which will only continue to increase with the complexity
of the page.
Not only has this reduced our network footprint dramatically, but it eliminates the necessity
for the server to instantiate the UpdatePanel’s controls and take them
through their life cycles to render the HTML sent back to the browser.