Tracy.Bai

Focus on Data analysis and Mining

导航

【翻译】为什么UpdatePanel是危险的!

假如你像我一样,无法抵挡这种诱惑,一个页面上放很多个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点击之后将异步传回数据,让我们来看看发生了什么: 
为了传回22个字符,有惊人的数据来回传输。
用Page Methods
PageMethod代替了postback以及接收到html标记语言来代替整个UpdatePanel的内容,我们仅仅使用一个web method
来获取我们感兴趣的内容,
<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:

JSON Response

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.

posted on 2008-08-09 16:34  Love Fendi  阅读(257)  评论(0编辑  收藏  举报