Dynamically changing Master Template in ASP.NET MVC
Asked Answered
M

3

5

I have the requirement to support different Master pages on my application (ASP.NET MVC). What is the recommended way to:

  1. Pass the master page name to the view from.
  2. Store the master page (in session, or something) so it sticks during a user's visit.
Milkmaid answered 7/11, 2008 at 14:54 Comment(0)
I
9

Use a custom base controller and inherit from it instead:

Public Class CustomBaseController
    Inherits System.Web.Mvc.Controller

    Protected Overrides Function View(ByVal viewName As String, ByVal masterName As String, ByVal model As Object) As System.Web.Mvc.ViewResult

       Return MyBase.View(viewName, Session("MasterPage"), model)

    End Function

End Class

I set my Session variable in the global.asax Session_Start:

Sub Session_Start(ByVal sender As Object, ByVal e As EventArgs)

//programming to figure out your session
Session("MasterPage")="MyMasterPage"

End Sub
Indaba answered 20/1, 2009 at 11:1 Comment(1)
This is an excellent answer, just to update it slightly in MVC3 you can also now create custom Razor View Engine which may be cleaner: weblogs.asp.net/imranbaloch/archive/2011/06/27/…Undirected
B
0

you could throw the master page name into the session, but sessions are unreliable. i'd recommend throwing it in a db instead.

once you're in the page, you can change/set the master page by accessing page.masterpagefile. it's a string; just pass the .master name in.

Breughel answered 7/11, 2008 at 15:12 Comment(0)
C
-2

Why not keep the Master Page on the user profile? Then just change it on the PreLoad event.

http://www.odetocode.com/articles/440.aspx

Carnarvon answered 7/11, 2008 at 15:20 Comment(3)
I'm using ASP.NET MVC. Shouldn't the controller decide what page to use?Milkmaid
yep. Probably you should use a base controller.Carnarvon
The question specifically mentions that it's for ASP.NET MVC and not ASP.NETFoppery

© 2022 - 2024 — McMap. All rights reserved.