动态更改母版页..从母版页?
我有以下代码:
public abstract class BasePage : Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
if (IsPostBack)
return;
var section = ConfigurationManager.GetSection("UrlRewriter/PlainRules");
if (section == null)
SetMaster("~/App_Shared/Master/BaseRegular.Master");
else
SetMaster("~/App_Shared/Master/BaseRewritable.Master");
}
protected void SetMaster(string value)
{
MasterPage master = Master;
while (master != null)
{
if (master is SharedMaster)
{
master.MasterPageFile = value;
break;
}
master = master.Master;
}
}
}
它在动态更改母版页方面效果很好,但我希望能够直接从 SharedMaster
执行此操作,而不是从我拥有的每个页面执行此操作。
如果放置在母版页上,Page_PreInit 永远不会触发,那么我该如何实现这一点呢?
I have the following piece of code:
public abstract class BasePage : Page
{
protected void Page_PreInit(object sender, EventArgs e)
{
if (IsPostBack)
return;
var section = ConfigurationManager.GetSection("UrlRewriter/PlainRules");
if (section == null)
SetMaster("~/App_Shared/Master/BaseRegular.Master");
else
SetMaster("~/App_Shared/Master/BaseRewritable.Master");
}
protected void SetMaster(string value)
{
MasterPage master = Master;
while (master != null)
{
if (master is SharedMaster)
{
master.MasterPageFile = value;
break;
}
master = master.Master;
}
}
}
It works great in changing my master pages dynamically, but I'd want to be able to do this directly from SharedMaster
, rather than from every single page I have.
Page_PreInit doesn't ever fire if placed on the master page, so how can I accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
如果您将此功能放入
BasePage
中,然后从BasePage
继承每个页面,则无需在每个页面中重复该代码。您似乎已经拥有完美的工作代码。至于将逻辑放入母版页中,这是不可能的 - 因为一旦母版页与页面关联并且加载控制树,您就无法更改母版页。 pre_init 不会触发母版页,因为母版页在此之前不会加载,因此一旦可以更改与该页面关联的母版页。然后加载母版页并创建复合控制树,之后您将收到母版页事件。
If you put this functionality in
BasePage
and then inherit each of your page fromBasePage
then you don't have to repeat the code in every page. You already seems to have a perfect working code.As far as putting the logic in master page, it will not be possible - because once master page gets associated with the page and control tree is loaded, you cannot change the master page. The pre_init does not trigger for master page because master page is not loaded till that point and so once can change the master page associated with the page. Then master page is loaded and a composite control tree gets created and after that you will receive master page events.