【问题标题】:Master Page load not being called没有调用母版页加载
【发布时间】:2025-11-26 06:15:01
【问题描述】:
 public partial class MasterPage : System.Web.UI.MasterPage
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(System.Web.HttpContext.Current.User.Identity.Name != "") //if (!Page.IsPostBack)
            {
                BusinessLayer.ShoppingCart cart = new BusinessLayer.ShoppingCart();
                int count = cart.getNoOfProducts(System.Web.HttpContext.Current.User.Identity.Name);
                Label lblCart = (Label)Master.FindControl("lblCartNo");
                lblCart.Text = " (" + count + ")";
            }
        }
    }

我放置了一个断点并且这段代码永远不会被调用(即使没有 if 语句),我也无法找到位于母版页中的标签

【问题讨论】:

    标签: asp.net master-pages


    【解决方案1】:

    为了调用 Page_Load,请确保在您的 MasterPage.aspx 中有 AutoEventWireup="true":

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="Mysite.Website.Templates.MasterPages.Site" %>
    

    确保 MasterPage.aspx Inherits 属性与您的代码隐藏命名空间和类名以及您的 .designer.cs 命名空间和类匹配。

    如果 aspx 和代码隐藏文件都正确连接,那么您应该能够删除 FindControl 语句。

    【讨论】:

    • 感谢您的回复,我刚刚意识到我的母版页中缺少此内容。但是我无法正确手动输入。
    • 我应该在 Inherits= 中输入什么?
    • 继承应该包含完全限定的类名。转到您的代码隐藏 .cs 文件。将该命名空间与您的类名结合起来,并将您的 Inherits 属性设置为该字符串。在我的示例中,命名空间是“Mysite.Website.Templates”,类名是“Site”。如果这看起来令人困惑,那么尝试添加一个新的 MasterPage 并移动所有标记 + 代码隐藏。 Visual Studio 应该为您正确连接文件。
    【解决方案2】:

    您的母版页的 Page_Load 事件肯定会触发。不知道为什么你的断点没有被命中,但要仔细检查,我建议尝试一些更暴力的方法,以确保绝对没有调用该方法:

    protected void Page_Load(object sender, EventArgs e)
    {
        Response.Write("Page_Load");
        Response.End();
    }
    

    由于控件嵌套的方式,可能找不到您的标签,因为 Master.FindControl 如果控件位于另一个控件中,则将不起作用。我建议查看“Finding controls inside of nested master pages”,它有一个有用的帮助方法,可用于递归搜索控件。

    【讨论】:

      最近更新 更多