开发者

C# ASP.NET MasterPage nested inheritance is evil

开发者 https://www.devze.com 2023-01-19 13:02 出处:网络
I have a solution with quite a few different MasterPages / BasePages which all inherit from somewhere else. My problem is that I have a virtual string in BaseMaster, which is overridden by BaseManagem

I have a solution with quite a few different MasterPages / BasePages which all inherit from somewhere else. My problem is that I have a virtual string in BaseMaster, which is overridden by BaseManagement, but when I try to access this string I always get the base value

The point of inheriting masters and pages is obviously to avoid having duplicate code everywhere.

Maybe it has something to do with the fact that I "need" protected void Page_Load(object sender, EventArgs e) at every master no matter

C# ASP.NET MasterPage nested inheritance is evil

So, here's an snippet from Base.Master.cs

public abstract partial class BaseMaster : MasterPage, IRewritablePageElement
{
    public BasePage BasePage { get { return Page as BasePage; } }
    public BaseMaster Self { get { return (BaseMaster)this.Page.Master; } }
    public virtual string accessUri { get { return "/"; } }
    public string AccessUri { get { return Self.accessUri; } }

    protected void Page_Load(object sender, EventArgs e)
    {
        this.OnPageLoad(sender, e);
    }

    /// <summary>
    /// If we want to do something on page load, we override the following method
    /// </summary>
    public virtual void OnPageLoad(object sender, EventArgs e)
    {
        SetCacheability();

        RedirectSiteDown();
        RedirectUnregisteredUsers();
        RedirectUnprivilegedUsers();

        if(!IsPostBack)
        {
            PopulateMenu();

            ...

As you already noticed,

    public BaseMaster Self { get { return (BaseMaster)this.Page.Master; } }
    public virtual string accessUri { get { return "/"; } }
    public string AccessUri { get { return Self.accessUri; } }

is as ugly as it get开发者_如何学运维s, since it should just be

    public virtual string AccessUri { get { return "/"; } }

but the code somehow manages to get all the way down to a level where AccessUri is "/" even though it has been overriden with "/a/" somewhere at a higher level:

public partial class BaseManagementMaster : BaseMaster
{
    public override string accessUri { get { return "/a/"; } }

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

If not for the Self thingy, here AccessUri is still "/". which makes absolutely no sense. Also, the fact that I have to re-declare Page_Load methods makes very little sense too.

Is there a clean way to do master page inheritance, is it even realistically possible?


the problem was in inheriting masterpages like

BaseManagementMaster : BaseMaster

this is wrong, the correct way to do this should be to just declare MasterPages, and then have abstractions at Page level, not Master level.

0

精彩评论

暂无评论...
验证码 换一张
取 消