C# – Accessing a Property of a Master Page from a class that’s not part of a content page in ASP.NET

asp.netcmaster-pages

So I'm wiring up my first MasterPage, and everything is working great except for one thing. This is a legacy app, and I have an old BasePage class that all my content pages inherit. It inherits from System.Web.UI.Page, but has no content itself (no .aspx file). It runs a bunch of the user authentication/role granting menu building. I want to keep this functionality but use it to set controls on my MasterPage to build out the menus. I cannot for the life of me figure out how to reference the MasterPage properties without a MasterType declaration in a content page.

My MasterPage class is called NIMS_Master, and I have the following in it (just trying to get started):


public partial class NIMS_Master : System.Web.UI.MasterPage
{
public string MenuList { get; set; }

    protected void Page_Load(object sender, EventArgs e)
    {}
  }

With a MasterType declaration in one of my content pages:

<%@ MasterType VirtualPath="~/NIMS_Master.master" %>

I can access my property in Login.aspx.cs as follows:


this.Master.MenuList = "this is the menu list";

But in my BasePage.cs, I have nowhere to put the MasterType declaration. All the google searches indicate I have to cast my NIMS_Master class as a Master, but I cannot get it to work to save my life. I've tried several different things, but my NIMS_Master class just doesn't show up in BasePage.


((this.Master)NIMS_Master).MenuList = "This is a menu list";

BasePage.cs is in my App_Code directory and my MasterPage file is in the application root, if that matters.

Best Answer

As I see it, your cast should be: ((NIMS_Master)this.Master).MenuList