Asp.net

ASP.NET AJAX:頁面載入完成後觸發 UpdatePanel

  • November 15, 2013

我確定這很容易,但我無法弄清楚:

我有一個 ASP.NET 頁面,上面有一些 UpdatePanel。我希望頁面完全載入更新面板中的一些“請稍候”文本。然後,一旦頁面完全載入,我想呼叫一個程式碼隱藏函式來更新 UpdatePanel。

關於實現這個想法需要什麼 Javascript 和程式碼隱藏的組合的任何想法?

PS:我嘗試將我的函式呼叫放在 Page_Load 中,但是程式碼在頁面傳遞之前執行,並且由於我要執行的函式需要一些時間,所以頁面載入時間太長。

我擺弄了 ScriptManager 的建議——我認為我最終會開始工作,但在我看來,Timer 的想法更容易實現,而且並不是真的(!)那麼大的黑客?!

這是我在初始頁面渲染完成後更新面板的方式…

預設.aspx

   <%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="AJAXPostLoadCall._Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
   <title>Untitled Page</title>
</head>
<body>
   <form id="form1" runat="server">
   <h2>And now for a magic trick...</h2>
   <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePartialRendering="True">
       </asp:ScriptManager>
       <div>
           <asp:UpdatePanel ID="UpdatePanel1" runat="server">
               <ContentTemplate>
                   <asp:Timer ID="Timer1" runat="server" Interval="2000" ontick="Timer1_Tick" />
                   <asp:Label ID="Label1" runat="server">Something magic is about to happen...</asp:Label>
               </ContentTemplate>
           </asp:UpdatePanel>

       </div>
   </form>
</body>
</html>

和 default.aspx.cs 後面的程式碼讀取

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

namespace AJAXPostLoadCall
{
   public partial class _Default : System.Web.UI.Page
   {

       protected void Page_Load(object sender, EventArgs e)
       {
       }

       public void DoMagic()
       {
           Label1.Text = "Abracadabra";
       }

       protected void Timer1_Tick(object sender, EventArgs e)
       {
           // Do the magic, then disable the timer
           DoMagic();
           Timer1.Enabled = false;
       }

   }
}

因此,頁面載入並且計時器(包含在 UpdatePanel 中)在頁面載入後 2 秒觸發(我認為 - 我不確定計時器何時實際啟動?)。標籤文本被重寫,然後定時器被禁用以停止任何更新。

很簡單——但是你能告訴我這是否是一個可怕的黑客嗎?

看看ScriptManager.RegisterStartupScript

這個想法是您註冊一個腳本以在啟動時執行(我相信一旦頁面載入)。您的腳本應該呼叫一個函式,該函式會通過您的 UpdatePanel 進行回發

引用自:https://stackoverflow.com/questions/31935