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

跟風遠走 提交于 2019-12-08 06:15:01

问题


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?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/2639449/how-to-create-create-variables-properties-in-master-page-and-let-sub-pages-acce

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