2015-01-09 32 views
0

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

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

+0

这并不困难..你有没有做过谷歌搜索..?有很多的例子,这里有一个例子在这里http://stackoverflow.com/questions/3651326/asp-net-access-a-master-page-variable-through-content-page – MethodMan

回答

1

我认为你想说,你要访问的变量在从母版抗衡页面,如果是正确的,用这个例子:

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

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

在其他情况下,如果你真的想从母版访问在ContentPage变量,你只可以设置会话值,然后在母版阅读。例如:

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

} 

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

+0

你也可以使用'<%@ MasterType TypeName =“(type)”%>'。 – pseudocoder

+0

您可能想提及此方法不能从母版页访问内容页面,而是允许内容页面访问母版页成员。根据情况,这可能不适用于该操作。 – pseudocoder

+0

是的你确定,我想他想说这个。因为另一个案例看起来很容易回答。我会编辑提到的帖子,谢谢你。 –