Set Property Value on Master Page from Content Page

那年仲夏 提交于 2019-11-30 09:44:49
Michael Kniskern

Create a property in your master page and you access it from content page:

Master page:

public partial class BasePage : System.Web.UI.MasterPage
{
    private string[] _RequiredRoles = null;

    public string[] RequiredRoles
    {
        get { return _RequiredRoles; }
        set { _RequiredRoles = value; }
    }
}

Content Page:

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load()
    {
        Master.RequiredRoles = new string[] { /*set appropriate roles*/ };
    }
}

Add page directive to your child page:

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

Then add property to your master page:

public string Section { get; set; }

You can access this property like this:

Master.Section = "blog";
NotMe

Typecast Page.Master to your master page so that you are doing something like:

((MyMasterPageType)Page.Master).Roles = "blah blah";

I'd go by creating a base class for all the content pages, something like:

public abstract class BasePage : Page
{
    protected abstract string[] RequiredRoles { get; }

    protected override void OnLoad(EventArgs e)
    {
        base.OnLoad(e);

        // display the required roles in a master page
        if (this.Master != null) {
            // value-assignment
        }

    }
}

And then I make every page inherits from BasePage, and each defining a RequiredRoles

public partial class _Default : BasePage
{
    protected override string[] RequiredRoles
    {
        get { return new[] { "Admin", "Moderator" }; }
    }
}

This has the advantage of cleanliness and DRY-ing the OnLoad handler code. And every page which inherits from BasePage are required to define a "RequiredRoles" or else it won't compile.

CType(Master.FindControl("lblName"), Label).Text = txtId.Text CType(Master.FindControl("pnlLoginned"), Panel).Visible = True

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