asp.netmaster-pages

ASP.NET MasterPage can't access it's own Label from code behind


I have a weird issue where I have a MasterPage, inside it a simple navbar with labels. For example I have the following label in the Site.Master:

<asp:Label ID="TestLabel" runat="server" CssClass="badge bg-danger"/>

But when I try to access it from the Page_Load of the MasterPage by saying:

TestLabel.Text = "test text"

Then I simply get the error saying "The name 'LostCount' does not exist in the current context". I'm not quite sure why, because I did similar MasterPages before, where the same thing happens - label in MasterPage markup, set value on Page_Load - and it works just fine.

Just to clarify, I am trying to access this label from the Page_Load of the MasterPage itself - not the content page. The MasterPage should have no issue accessing it's own element, right?


Solution

  • Okay, as I was just about to send this question, I have found the cause. The top markup of the MasterPage included the .cs file as CodeBehind.

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="ProjectName.SiteMaster" %>
    

    Changing it to CodeFile solves the issue, now I can access the Label properly.

    <%@ Master Language="C#" AutoEventWireup="true" CodeFile="Site.master.cs" Inherits="ProjectName.SiteMaster" %>