简体   繁体   中英

Referencing MasterPage from WebUserControl included in that MasterPage

I am accesing a MasterPage public object from a Web User Control, for doing that, I have to reference the MasterPage in the WUC, and since I am going to use that WUC in the MasterPage as well I have to reference the WUC from the MasterPage. .Net tells me that this is a circular reference and that it is not allowed.

My question is: Can I access a MasterPage object from the Web User Control if im using it on the same MasterPage too?

Let's go step to step:

First, I have a namespace for the MasterPage and this object declared:

namespace MyMPNamespace {
public partial class SiteMaster : System.Web.UI.MasterPage
{
    public MyNamespace.Navigator Navi {get; set;}
    public MyNamespace.user User { get; set; }

    protected void Page_Init(object sender, EventArgs e) {
        Navi = new MyNamespace.Navigator();
        User = new MyNamespace.user(true, true);
    }
...
} }

Then I can access it from a Web User Control, first, referencing the MasterPage:

<%@ Register TagPrefix="mp" TagName="MyMP" Src="~/Site.master" %>

Then, accessing it using the namespace I created:

public MyNamespace.Navigator Navigator { get; set; }

protected void Page_Load(object sender, EventArgs e)
{
    Navigator = ((MyMPNamespace.SiteMaster)this.Page.Master).Navi;
}

That done, it works on any .aspx page. But now I wanted to add that WUC to the MasterPage and I found I can't because .Net says there is a circular reference (and is true, but shouldn't be a problem).

I know of other ways of doing this, like loading the WUC dynamically (ive not tried it), or accesing the WUC from the MasterPage and setting the WUC property from there (this works). What I want to know is, if there is a way of doing this reference because I like the idea of the WUC being able to access the MasterPage and be 100% independent, it knows what to display etc. not having to call it at all.

I was able to create a Web User Control, place it on a master page, and then access the master page with no circular reference issue. In order to answer, I would need a little more information:

  1. What version of .NET are you using?
  2. Are you using a web site or a web application?
  3. Is the user control created in the same source file as the master page?
  4. If not, why would you register the user control using Site.master as the Src?
  5. The user control in question is being placed on the web page and master via the designer?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM