Button與頁面回遞

來源:互聯網
上載者:User
    事情起因:
    今天,在做項目的時候,頁面中用了兩個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事件,竟然不知道事件觸發時,系統到底做了哪些工作,導致了這個錯誤。哎,看來以後學習還是得多上點心啊。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.