asp.net mvc - Is ViewPageBase the right place to decide what master page to load? -


as can tell title, i'm n00b mvc. i'm trying decide master load based on route configuration settings. each route has masterpage property (in addition usual url, controller , action properties) , i'm setting masterpage in onpreinit event of viewpagebase class (derived viewpage). however, i'm not sure if mvc way of doing it? need controller supplies masterpage info view?

here's code snippet.

public class viewpagebase : viewpage {     protected override void onpreinit(eventargs e)     {         routeelement currentroute = mvcroutes.getcurrentroute();          //set master page         this.masterpagefile = string.isnullorempty(currentroute.masterpage) ?                                mvcconfiguration.defaultmasterpage : currentroute.masterpage;                 base.onpreinit(e);     }  } 

i'm huge fan of ignoring seems webformish , trying find right mvc hook. in case creating custom view engine correct extensibility hook this. if think engine decides .aspx file render should decide mater page aspx file uses. here semi-psuedo ( i've never compiled ) code should work.

public class dynamicmasterviewengine: virtualpathproviderviewengine  { public dynamicmasterviewengine() {                  /* {0} = view name or master page name    * {1} = controller name      */     masterlocationformats = new[] {        "~/views/shared/{0}.master"    };     viewlocationformats = new[] {        "~/views/{1}/{0}.aspx",        "~/views/shared/{0}.aspx"  };     partialviewlocationformats = new[] {        "~/views/{1}/{0}.ascx",                    };  }  protected override iview createpartialview(controllercontext controllercontext, string partialpath) {     throw new notimplementedexception(); }  protected override iview createview(controllercontext controllercontext, string viewpath, string masterpath) {      return new webformview(viewpath, masterpath ); }  public override viewengineresult findview(controllercontext controllercontext, string viewname, string mastername, bool usecache) {     routeelement currentroute = mvcroutes.getcurrentroute();      var mastername = string.isnullorempty(currentroute.masterpage) ?                            mvcconfiguration.defaultmasterpage : currentroute.masterpage;             return base.findview(controllercontext, viewname, mastername, usecache); }  protected override bool fileexists(controllercontext controllercontext, string virtualpath) {     return base.fileexists(controllercontext, virtualpath); }         } 

ported this answer


Comments

Popular posts from this blog

c++ - How do I get a multi line tooltip in MFC -

asp.net - In javascript how to find the height and width -

c# - DataTable to EnumerableRowCollection -