ServerClick 事件触发 Page.Load

ServerClick event fires Page.Load

最近我在 asp.net 中发现了一个问题,这对我来说有点奇怪。

我有一个 sample.aspx 文件:

<%@ Page Language="vb" AutoEventWireup="false" CodeBehind="sample.aspx.vb" Inherits="SampleProj.sample" MasterPageFile="~/Site.Master" %>

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
    <input type="image" id="Accept" runat="server" class="accept-btn" src="/Images/accept.png" />
</asp:Content>

以及相关的代码隐藏文件sample.aspx.vb:

Public Class sample
   Inherits System.Web.UI.Page

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
'Some code here
End Sub

Private Sub Accept_ServerClick(sender As Object, e As ImageClickEventArgs) Handles Accept.ServerClick
'Some code here
End Sub

所以我的问题很容易解释:单击接受按钮后,Accept.ServerClick 事件按预期触发,但由于某种原因(即使页面未重新加载)Page.Load 事件是也被解雇了这是我的第一个 asp 项目,也许这是一种预期的行为,但我既没有找到解释也没有找到禁用它的方法。如有任何信息,我们将不胜感激。

你好,Ohemgi

(如果您发现任何错误,这是由于编写这个简短示例引起的。我的代码编译和运行没有问题,所以我的问题只是关于加载事件)

很好。来自 MSDN 文档:

After a page has been posted back, the page's initialization events (Page_Init and Page_Load) are raised, and then control events are processed.

如果您在 Page_Load 中做了一些您不想在每次单击按钮时都做的事情,只需将其包装在这个条件中:

if (!Page.IsPostBack)
{
    // Some code here. It is executed only once.
}

您可以在以下链接中找到更多信息:

  1. ASP.NET Web Server Control Event Model
  2. ASP.NET Page Life Cycle Overview

VB.Net版本

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
    If Not Page.IsPostBack Then
        ' Some code here. It is executed only once.
    End If
End Sub