0

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

如何从母版页引用公共内容页面变量?

4

1 回答 1

1

我想您想说您想从竞争页面访问 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"%>

然后您可以使用 MasterPage 的公共变量,使用 Master.NameVariable。

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";
        }
    }

}

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

于 2015-01-09T17:36:39.353 回答