2011-09-26 33 views
1

Default.aspx中我有下面的代碼,一個asp.net頁面結構問題

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
</head> 
<body> 
Place 1 
    <form id="form1" runat="server"> 
    Place 2 
    <br /> 
    <div> 
     <asp:Button ID="Button1" runat="server" Text="Button" onclick="Button1_Click" /> 
    </div> 
    </form> 
</body> 
</html> 

我把頁面上的一個按鈕上寫「我點擊了!」。

而隱藏代碼:

public partial class Default : System.Web.UI.Page 
{ 
    protected void Page_Load(object sender, EventArgs e) 
    { 
     Button1.Text = "Button";   
    } 
    protected void Button1_Click(object sender, EventArgs e) 
    { 
     Response.Write("I am clicked!"); 
    } 
} 

當我建,網頁的看法是象下面這樣:

Place 1 
Place 2 
Button 

當我按一下按鈕, 「我點擊了!」前廣場1

結果似乎是:

I am clicked! Place 1 
Place 2 
Button 

它爲什麼會「將1」之前出現? 你有什麼想法嗎?

+0

你可能要考慮的ASP.NET頁面生命週期http://msdn.microsoft.com/en-us/library/ms178472.aspx更好地理解爲什麼發生這種情況,但下面的答案是正確的。 –

回答

2

由於控制事件PreRender頁事件之前處理。因此,所有頁面內容都將在控制事件處理程序中手動輸出後呈現。

基本上,你不應該這樣做使用Response.Write(),簡單地說:

button.Text ="I am clicked!"; 

MSDN - ASP.NET Page Life Cycle

控制事件 使用這些事件來處理特定控件事件,如Button 控件的Click事件或TextBox控件的TextChanged事件。

enter image description here

5

因爲您直接在回覆中寫入。如果你想對網頁上的特定位置的文本,把一個asp:Label控件的頁面上,並設置標籤控件的Text屬性在Button1_Click的

3

這是可以預料的 - 看看Page-Live-Cycle

請注意,渲染回發事件處理

Normaly你不使用的Response.Write把控制或ASP-才能輸出標籤的東西在ASP.net