C# 如何动态设置母版页?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10930965/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-09 15:48:31  来源:igfitidea点击:

How to Set Master Page dynamically?

c#.netmaster-pagesmaster

提问by Amol Kolekar


I have requirement in which i want to set different Master Pages for the Same Page depending upon userid(i.e. for one user it must set one master page and for another user it must set another master ).Can we set different Master pages for any page dynamically?Please help...


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

采纳答案by Kapil Khandelwal

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 阶段动态分配母版页。

回答by Connell

You can, by setting the MasterPageFileproperty of the Page. However, this will throw an InvalidOperationExceptionif it is called after the PreInitevent. Have a look at the ASP.NET Page Lifecycle

您可以通过设置页面的MasterPageFile属性。但是,InvalidOperationException如果在PreInit事件之后调用它,则会抛出一个。查看ASP.NET 页面生命周期

The MasterPageFile property can be set only in the PreInit event; attempting to set the MasterPageFile property after the PreInit event will throw an InvalidOperationException exception. 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 属性只能在 PreInit 事件中设置;在 PreInit 事件之后尝试设置 MasterPageFile 属性将引发 InvalidOperationException 异常。如果 MasterPageFile 属性无效,则会在页面生命周期的后期抛出 HttpException 类型的异常,但在 PreInit 事件中设置该属性时不会抛出异常。

回答by Joshua

Please note this article on MSDN:

请注意 MSDN 上的这篇文章:

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

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

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