How do I reference an ASP.net MasterPage from App_Code

你。 提交于 2019-11-29 07:50:35

I've tended to do the following with Web Site projects:

In App_Code create the the following:

BaseMaster.cs

using System.Web.UI;

public class BaseMaster : MasterPage
{
    public string MyString { get; set; }
}

BasePage.cs:

using System;
using System.Web.UI;

public class BasePage : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (null != Master && Master is BaseMaster)
        {
            ((BaseMaster)Master).MyString = "Some value";
        }
    }
}

My Master pages then inherit from BaseMaster:

using System;

public partial class Masters_MyMasterPage : BaseMaster
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(MyString))
        {
            // Do something.
        }
    }
}

And my pages inherit from BasePage:

public partial class _Default : BasePage

I found some background to this, it happens because of the way things are built and referenced.

Everything in App_Code compiles into an assembly.

The rest, aspx files, code behind, masterpages etc, compile into another assemlby that references the App_Code one.

Hence the one way street.

And also why Ben's solution works. Thanks Ben.

Tis all clear to me now.

I realise there are already accepted solutions for this, but I just stumbled across this thread.

The simplest solution is the one listed in the Microsoft website (http://msdn.microsoft.com/en-us/library/c8y19k6h.ASPX )

Basically it says, your code will work as-is, if you include an extra directive in the child page aspx:

<%@ MasterType VirtualPath="~/MyMaster.Master" %>

Then you can directly reference the property in the base MyPage by:

  public string PageID
  {
        set
        {
            Master.PageID = value;
        }
        get
        {
            return Master.PageID;
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!