事情起因:
今天,在做項目的時候,頁面中用了兩個updatePanel,來實現頁面的非同步更新。用一個updatePanel中的Button來控制另一個updatePanel中內容的更新,奇怪的是其顯示的內容還是原來的內容。為簡單起見,我用一個簡單的例子來描述我項目中出現的問題。
首先頁面代碼:<body>
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
<div>
<asp:UpdatePanel ID="UpdatePanel1" runat="server">
<ContentTemplate>
<asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" />
<asp:Label ID="Label1" runat="server" Text="BeforeSubmit"></asp:Label>
</ContentTemplate>
</asp:UpdatePanel>
<asp:UpdatePanel ID="UpdatePanel2" runat="server" UpdateMode="Always">
<ContentTemplate>
<asp:TextBox ID="TextBox2" runat="server">
</asp:TextBox>
<asp:Button ID="Button2" runat="server" Text="Button" /></ContentTemplate>
</asp:UpdatePanel>
</div>
</form>
</body>
在頁面中我定義了兩個updatePanel,用updatePanel中的Button1來控制updatePanel2種的TextBox2的取值。後台代碼如下:
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TextBox2.Text = Label1.Text;
}
protected void Button1_Click(object sender, EventArgs e)
{
Label1.Text = "AfterSubmit";
}
}
在Page_Load()方法中修改TextBox2中的值,但執行結果:
TextBox2中的值並沒有像想象中的發生變化還是“Beforesubmit",但是再回遞頁面的話,TextBox2中的值就變成了“AfterSubmit”。
這是為什麼呢?通過設定斷點,發現,當Button回遞頁面的時候,先執行的是Page_Load()方法,然後再執行OnClick事件中的Button1_Click(object sender, EventArgs e)方法。這就是問題的根結。
說來真是慚愧,用了這麼多button的OnClick事件,竟然不知道事件觸發時,系統到底做了哪些工作,導致了這個錯誤。哎,看來以後學習還是得多上點心啊。