Setting an ASP.NET Master Page at runtime

前端 未结 6 1194
星月不相逢
星月不相逢 2021-02-04 15:45

I\'m working on a site which needs to be able to support two or more looks, changable at runtime. I\'d hoped to be able to handle the change with a CSS switch, but it looks like

6条回答
  •  别那么骄傲
    2021-02-04 16:23

    I feel your pain. I searched for about an hour (if not more) for an issue to this, without success. It isn't just a cut and dry answer to say "just call it from PreInit on each page" when you have hundreds of pages. But then I realized that I was spending more time looking for a solution than it would have taken to just do it on each page.

    However, I wanted to set the MasterPageFile based on a Profile property, so that would have been about 5 lines of code each page, a maintainability nightmare. And anyways, "don't repeat yourself", right?

    So I created an Extension method in a module in the App_Code folder to make this easier and more maintainable.

    Public Module WebFunctions
    
         _
        Public Sub SetMaster(ByVal page As Page)
    
            Dim pb As ProfileCommon = DirectCast(HttpContext.Current.Profile, ProfileCommon)
    
            If pb IsNot Nothing Then
                page.MasterPageFile = pb.MasterPage
            End If
    
        End Sub
    
    End Module
    

    And then on each page's PreInit, I just call this:

    Protected Sub Page_PreInit(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreInit
            Me.SetMaster()
        End Sub
    

提交回复
热议问题