为什么我想要加载另一个页面时,Page_Load事件会触发?

3

我对ASP非常陌生,有一个感觉非常基础的问题需要解决。我在default.aspx.cs文件中有以下代码:

        protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Get one day ago
            DateTime oneDayAgo = DateTime.Now.ToLocalTime().AddDays(-1);
            String strOneDayAgo = oneDayAgo.ToString();

            //Declare the query string
            String queryString = "Select * from Computers Where whenCreated >= '" + strOneDayAgo + "' ORDER BY whenCreated DESC";

            //Show the query being used to the user
            lblQueryUsed.Text = queryString;

            // Run the query and bind the resulting DataSet to the GridView control.
            DataSet ds = GetData(queryString);
            if (ds.Tables.Count > 0)
            {
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
    }

所有的内容都运作得非常好,但是问题出现在当用户点击该页面上的链接以进入另一个名为Reports.aspx的页面时,同样的Page_Load事件被触发,并且所有控件(lblQueryUsed、GridView1)由于某种原因都被设置为NULL,导致我收到了异常信息。
为什么我想要加载Reports.aspx时,default.aspx的Page_Load事件会被加载?为什么这些控件为空?
非常感谢您的帮助。
编辑:这是该页面的全部代码,请问还需要什么?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.DirectoryServices;
using System.Data.SqlClient;
using Sorter;
using System.Data;

namespace AD_watcher_web_app
{
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            //Get one day ago
            DateTime oneDayAgo = DateTime.Now.ToLocalTime().AddDays(-1);
            String strOneDayAgo = oneDayAgo.ToString();

            //Declare the query string
            String queryString = "Select * from Computers Where whenCreated >= '" + strOneDayAgo + "' ORDER BY whenCreated DESC";

            //Show the query being used to the user
            lblQueryUsed.Text = queryString;

            // Run the query and bind the resulting DataSet to the GridView control.
            DataSet ds = GetData(queryString);
            if (ds.Tables.Count > 0)
            {
                GridView1.DataSource = ds;
                GridView1.DataBind();
            }
        }
    }

    protected void Label1_PreRender(object sender, EventArgs e)
    {
        //Populate the labels
        lblCompCount.Text = GridView1.Rows.Count.ToString();
        lblTimeRun.Text = DateTime.Now.ToLocalTime().ToString();
    }

    ///////////////////////METHODS///////////////////////

    DataSet GetData(String queryString)
    {
        // Set the connection string
        SqlConnectionStringBuilder conBuilder = new SqlConnectionStringBuilder();
        conBuilder.DataSource = "dbsql01dev.llnl.gov";
        conBuilder.InitialCatalog = "XloadDB";
        conBuilder.IntegratedSecurity = true;

        String connectionString = conBuilder.ConnectionString;

        //Declare a new dataset
        DataSet ds = new DataSet();

        try
        {
          // Connect to the database and run the query.
          SqlConnection connection = new SqlConnection(connectionString);        
          SqlDataAdapter adapter = new SqlDataAdapter(queryString, connection);

          // Fill the DataSet.
          adapter.Fill(ds);
        }
        catch(Exception ex)
        {
          // The connection failed. Display an error message.
            lblExceptions.Text = ex.ToString();
            lblExceptions.Visible = true;
        }
        return ds;
      }
}
}

这个链接是服务器端链接吗? - Oded
3
这些链接是在服务器上处理还是在客户端处理?换句话说,您是否在服务器上为它们的点击事件编写了处理程序,并执行了 Response.Redirect,还是这些只是简单的超链接? - zimdanen
1
请粘贴相关的aspx代码片段。 - Claudio Redi
2
如果链接导致页面回传,那么您的页面将重新加载。 - Rahul
我的链接看起来像这样,并且位于Site.Master上:<asp:MenuItem NavigateUrl="~/About.aspx" Text="关于"/> - Dbloom
1个回答

8
为了让服务器端控件正常工作,需要在控件事件触发之前重新加载页面。
这是页面生命周期的一部分。
这种行为也会出现在服务器端链接上 - 一旦发生后台回发,页面将重新加载并触发 page_load 事件。
为了避免这种情况,请将您的链接转换为纯客户端链接。
因此,不要使用 runat="server",而是使用正确的 HTML 链接格式 link

我担心OP没有发布完整的代码,而是在做其他事情。即使他正在进行Response.Redirect并且没有检查IsPostback,也没有理由在Page_Load上将这些控件设置为null。 - Icarus
以下是我的Site.Master上菜单栏的ASP代码: <asp:Menu ID="NavigationMenu" runat="server" CssClass="menu" EnableViewState="false" IncludeStyleBlock="false" Orientation="Horizontal"> <Items> <asp:MenuItem NavigateUrl="/Default.aspx" Text="主页"/> <asp:MenuItem NavigateUrl="/Reports.aspx" Text="报告" /> <asp:MenuItem NavigateUrl="~/About.aspx" Text="关于我们"/> </Items> </asp:Menu> - Dbloom
我一直在尝试使用客户端来创建链接,但是我的Site.Master文件顶部有<head runat="server">这一行,这是否意味着<head>标签中的所有内容都是服务器端的? - Dbloom
@Dbloom - head 元素没有必要在服务器端。除非你正在服务器端操作其内容。 - Oded
好的,我删除了Reports.aspx页面并添加了一个新页面。现在它可以工作了。感谢您的所有帮助,我比以前更懂了,但除了删除之前存在的从默认继承的内容,我不确定我做了什么来修复这个问题... - Dbloom
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接