Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
330 views
in Technique[技术] by (71.8m points)

c# - How do I reference an ASP.net MasterPage from App_Code

I'm working on a .net 3.5 site, standard website project.

I've written a custom page class in the sites App_Code folder (MyPage).

I also have a master page with a property.

public partial class MyMaster : System.Web.UI.MasterPage
{
...
    private string pageID = "";

    public string PageID
    {
        get { return pageID; }
        set { pageID = value; }
    }
}

I'm trying to reference this property from a property in MyPage.

public class MyPage : System.Web.UI.Page
{
...
        public string PageID
        {
            set
            {
                ((MyMaster)Master).PageID = value;
            }
            get
            {
                return ((MyMaster)Master).PageID;
            }
        }
}

I end up with "The type or namespace name 'MyMaster' could not be found. I've got it working by using FindControl() instead of a property on the MyMaster page, but IDs in the master page could change.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...