简体   繁体   English

如何动态设置母版页?

[英]How to Set Master Page dynamically?


我有一个要根据用户ID为同一页面设置不同母版页的要求(即,对于一个用户,它必须设置一个母版页,对于另一个用户,它必须设置另一个母版页)。我们可以为任何页面设置不同的母版页吗?动态吗?请帮忙...

void Page_PreInit(Object sender, EventArgs e)
{
    this.MasterPageFile = "~/MyMaster.master";
}

Explanation: You can attach a master page dynamically to a content page. 说明:您可以将母版页动态附加到内容页。 Because the master page and content page are merged during the initialization stage of page processing, a master page must be assigned before then. 因为母版页和内容页在页面处理的初始化阶段合并,所以在此之前必须分配母版页。 Typically, you assign a master page dynamically during the PreInit stage. 通常,您在PreInit阶段动态分配母版页。

Please note this article on MSDN: 请注意这篇文章在MSDN上:

http://msdn.microsoft.com/en-us/library/c8y19k6h.aspx http://msdn.microsoft.com/zh-CN/library/c8y19k6h.aspx

void Page_PreInit(Object sender, EventArgs e)
{
    this.MasterPageFile = "~/NewMaster.master";
}

You can, by setting the MasterPageFile property of the Page. 您可以通过设置Page的MasterPageFile属性。 However, this will throw an InvalidOperationException if it is called after the PreInit event. 但是,如果在PreInit事件之后调用它,则会抛出InvalidOperationException Have a look at the ASP.NET Page Lifecycle 看看ASP.NET页面生命周期

The MasterPageFile property can be set only in the PreInit event; 只能在PreInit事件中设置MasterPageFile属性。 attempting to set the MasterPageFile property after the PreInit event will throw an InvalidOperationException exception. 在PreInit事件之后尝试设置MasterPageFile属性将引发InvalidOperationException异常。 If the MasterPageFile property is not valid, an exception of type HttpException is thrown later in the page life cycle, but no exception is thrown when the property is set in the PreInit event. 如果MasterPageFile属性无效,则在页面生命周期的稍后会引发HttpException类型的异常,但是在PreInit事件中设置该属性时,不会引发任何异常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM