An asp.net page structure question

In Default.aspx I have below code,

<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>

I put a button on the page to write "I am clicked!".

And codebehind:

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!");
    }
}

When I build, the view of page is like below:

Place 1
Place 2 
Button

When I click the button, "I am clicked!" is appeared before Place 1.

The result is:

I am clicked! Place 1
Place 2 
Button

Why does it appear before "Place 1"? Have you got any idea?

Upvotes: 1

Views: 265

Answers (3)

sll
sll

Reputation: 62564

Because control events are processed before page PreRender event. So all page content would be rendered after manual output within a control event handler.

Basically you should not do this using Response.Write(), simply:

button.Text ="I am clicked!"; 

MSDN - ASP.NET Page Life Cycle

Control events Use these events to handle specific control events, such as a Button control's Click event or a TextBox control's TextChanged event.

enter image description here

Upvotes: 2

Random Dev
Random Dev

Reputation: 52300

that's to be expected - look at the Page-Live-Cycle

Please observe that the rendering is after the postback event handling.

Normaly you don't use Response.Write put a control or asp-tag to output something in ASP.net

Upvotes: 3

Erich Horak
Erich Horak

Reputation: 435

Because you are writing directly in the response. If you want to have the text on specific position on the page, put an asp:label control on the page and set the Text property of the label control in the Button1_Click

Upvotes: 5

Related Questions