How to pass a value from Master page to content page in asp.net 4

asp.netmaster-pages

I have no idea why this won't work but I have a function on a master page that gets the logged in user and then displays information about that user on the master page. I want to be able to pass one property (the user Role to the other pages to use for logic flow. I can't seem to get the content pages to recognize the property.

The error message is
'System.Web.UI.MasterPage' does not contain a definition for 'Role' and no extension method 'Role' accepting a first argument of type 'System.Web.UI.MasterPage' could be found (are you missing a using directive or an assembly reference?)'

Any ideas?

public partial class SiteMaster : System.Web.UI.MasterPage
{

    private string role = "Manager";

    public string Role
    {
        get
        {
            return role;
        }
        set
        {
            role = value;
        }
    }
protected void Page_Load(object sender, EventArgs e)
    {
  ...get current logged in user data and display appropriate fields in the master page.
}

}

Content Page

<%@ Page Title="" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeBehind="Portal.aspx.cs" Inherits="Portal" ClientIDMode="AutoID" %>
<%@ MasterType VirtualPath="~/Site.Master" %>  

<%@ Register Assembly="AjaxControlToolkit" Namespace="AjaxControlToolkit" TagPrefix="asp" %>

content page.cs

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {

           string testRole = Master.Role;

        }
    }

Best Answer

The "Master" property on Page returns the type System.Web.UI.MasterPage. You need to cast it to your specific type (SiteMaster) before you can call that class's functions.

SiteMaster siteMaster = Master as SiteMaster;
if (siteMaster != null) { myVar = siteMaster.Role; }
Related Topic