views:

87

answers:

2

How to create create variables/properties in master page, and let sub-pages access them?

So my master will have a string property HomeUrl

How can any page that uses the master page access this property?

+2  A: 

You should use a base class for you master page which will define you properties:

public class BaseMasterPage : System.Web.UI.MasterPage
{
    public string HomeUrl {get; set; }
}

And then your master page should inherit from this BaseMasterPage class (as example):

// real master page
public partial class Common_MasterPages_Backend_Default : BaseMasterPage
{
}

After this you can access your property through Page.Master property:

BaseMasterPage baseMaster = (BaseMasterPage)Page.Master;
string homeUrl = baseMaster.HomeUrl;

from any page which uses this master page.

Alex
A: 

You can use inheritance to do that.

Suppose this:

  • Your Master is called Med_Instrumento.Master
  • Your webContent is called Med_Instrumento1.aspx

You can create another page (say Instrumentobase.aspx) and put there all the public/protected properties you like. This page must use the masterpage as well.

After that, change your Med_Instrumento1.aspx class to inherite from this page.

For instance: here is the code: The webcontentpage:

<%@ Page Language="C#" MasterPageFile="~/Med_Instrumentos.Master" AutoEventWireup="true" CodeBehind="Med_Instrumento1.aspx.cs"

the code behind:

 public partial class Med_Instrumento1 : InstrumentoBase

The base class:

<%@ Page Language="C#" MasterPageFile="~/Med_Instrumentos.Master" AutoEventWireup="true" CodeBehind="InstrumentoBase.aspx.cs" Inherits="Auscultacion.InstrumentoBase" Title="Untitled Page" %>

the code behind:

    public partial class InstrumentoBase : System.Web.UI.Page
    {

    public string INST_Emplazamiento
    {
             get {return "Some Value"  );}
    }
    public TextBox DevolverTextBoxdeMaster(string sNombreTextBox)
          {
             TextBox Texto;
             Texto = (TextBox)Master.FindControl(sNombreTextBox);
             return Texto;
          }
}

In your Med_Instrumento1.aspx you can use your INST_Emplazamiento property or your DevolverTextBoxdeMaster method.

Claudia