从Master Page获取价值

时间:2012-04-23 14:44:58

标签: asp.net vb.net master-pages

我有一个母版页(myMaster),我有一个变量(让我们调用myInteger)我想在外部类中访问。

通常我只是在我的aspx中执行此操作:<%@ MasterType VirtualPath =“myMaster.master”%>

然后我可以在我的代码中访问它:Master.myInteger ......

我的问题是我想在另一个类(没有.aspx)中访问它

我试过了  Master.MasterPageFile =“〜/ myMaster.master”  Master.AppRelativeVirtualPath =“myMaster.master”

但是Master.myInteger无法识别。

我不确定我想做什么是可能的......想知道这个变量吗?

2 个答案:

答案 0 :(得分:4)

所以你需要从不继承MasterPage的类中引用Page的属性?

我建议使用属性或构造函数来使用此值初始化此类。但如果你真的需要这种方式,你可以尝试使用HttpContect.Current.Handler

的方法
// works even in static context
static void foo()
{
    int myInteger = -1;
    var page = System.Web.HttpContext.Current.Handler as System.Web.UI.Page;
    if(page != null) myInteger = ((myMaster)page.Master).myInteger;
}

请注意,这很容易出错,并且还会将您的课程与MasterPage进行硬链接。

答案 1 :(得分:0)

从外部课程中尝试这样的事情:

var page = HttpContext.Current.Handler as Page;
if (page != null)
{
    var value = ((MasterPageName)page.Master).SomeProperty;
}

如果您无法从外部类访问母版页,则可以使用反射来访问属性或方法:

var page = HttpContext.Current.Handler as Page;
if (page != null)
{
    var value = page.Master.GetType().GetProperty("SomeProperty").GetValue(page.Master, null);
}
相关问题