ASP.NET - 事件

事件句柄(event handler)是一种针对给定事件来执行代码的子例程。

ASP.NET - 事件句柄

请看下面的代码:

<%
lbl1.Text="The date and time is " & now()
%>

<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
</form>
</body>
</html>

上面的代码什么时候会被执行?答案是:“我不知道. . .”

Page_Load 事件

Page_Load 事件是众多 ASP.NET 可理解的事件之一。Page_Load 事件会在页面加载时被触发,然后 ASP.NET 会自动调用子例程 Page_Load,并执行其中的代码:

<script runat="server">
Sub Page_Load
lbl1.Text="The date and time is " & now()
End Sub
</script>

<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
</form>
</body>
</html>

注释:该 Page_Load 事件不包含对象引用或事件参数!

显示这个例子

Page.IsPostBack 属性

Page_Load 子例程会在页面每次加载时运行。如果您仅希望在页面第一次加载时执行 Page_Load 子例程中的代码,您可以使用 Page.IsPostBack 属性。如果 Page.IsPostBack 属性为 false,则页面第一次被载入,如果为 true,则页面传回服务器(例如,通过点击表单上的按钮):

<script runat="server">
Sub Page_Load
if Not Page.IsPostBack then
  lbl1.Text="The date and time is " & now()
end if
End Sub

Sub Submit(s As Object, e As EventArgs)
lbl2.Text="Hello World!"
End Sub
</script>

<html>
<body>
<form runat="server">
<h3><asp:label id="lbl1" runat="server" /></h3>
<h3><asp:label id="lbl2" runat="server" /></h3>
<asp:button text="Submit" onclick="submit" runat="server" />
</form>
</body>
</html>

上面的例子仅在页面初次加载时创建 "The date and time is...." 这条消息。当用户点击 Submit 按钮时,submit 子例程将在第二个 label 创建 "Hello World!",但第一个 label 中的日期和时间不会改变。

显示这个例子