将公共内容页面变量放入母版页

时间:2015-01-09 16:18:13

标签: c# master-pages content-pages

我的内容页面中有一个公共变量,我需要在我的MasterPage中访问。所以我可以设置一个Javascript变量......

如何从主页面引用公共内容页面变量?。

1 个答案:

答案 0 :(得分:1)

我想你想说你想从Contend Page访问MasterPage中的变量,如果是正确的,请使用这个例子:

声明您的公共或受保护变量:

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

{
    public string strEmpresa = "NS";

    protected void Page_Load(object sender, EventArgs e)
    {

    }
}

在内容页面的开头设置以下指令:

<%@ MasterType  virtualPath="~/MasterPage.Master"%>

然后您可以使用Master.NameVariable。

来使用MasterPage的公共变量
protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            TextBox1.Text = Master.strEmpresa;
        }
    }

在其他情况下,如果您真的想从MasterPage访问ContentPage中的变量,您只需在Session中设置值,然后在MasterPage中读取。例如:

public partial class MasterPage : System.Web.UI.MasterPage
{
    protected void Page_Load(object sender, EventArgs e)
    {

        if (!IsPostBack)
        {
            if (Session["myVariable"] != null)
            {
                TextBox1.Text = Session["myVariable"].ToString();
            }
        }
    }
}

 public partial class WebFormMP_TestPublicVariable : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            Session["myVariable"] = "Test";
        }
    }

}

有很多方法可以实现这一目标。检查互联网;)。