views:

419

answers:

2

When is the MasterPageFile property of a view/page checked that it exists in ASP.NET MVC WebForms view engine?

What I want to do is have the following code not output the error:

Parser Error Message: The file '/SomePlaceThatDosentExist/Site.Master' does not exist.

Defined as such in my view's .aspx file:

<%@ Page Language="C#" MasterPageFile="~/SomePlaceThatDosentExist/Site.Master" Inherits="System.Web.Mvc.ViewPage" >

Where would I need to write some code to go in and define a valid MasterPageFile property?

I have tried the following in my custom ViewPage class that my views inherit

    public override string MasterPageFile
    {
        get
        {
            return base.MasterPageFile;
        }
        set
        {
            base.MasterPageFile = "~/RealPlace/Site.Master";
        }
    }

and tried the following also (in a custom view page class that my views inherit)

    protected override void OnPreInit(EventArgs e)
    {
        base.MasterPageFile = "~/RealPlace/Site.Master";
        base.OnPreInit(e);
    }

In both cases, the error I stated above is displayed.

From what I know, OnPreInit is the earliest point in a ViewPage's lifecycle, so is it possible to go even earlier in the lifecycle?

Note before you write and answer:

  • I know about return View("ViewName", "MasterPageName");
  • I know about dynamic master pages, but I want to accomplish this specific task
A: 

If you want to change how a masterpage is found you can implement your own viewengine:

public CustomViewEngine()
{
    MasterLocationFormats = new string[] {
        "~/RealPlace/Site.Master""
    };
}
Malcolm Frexner
Doesn't that code only apply for for return View("ViewName", "MasterPageName");? Won't this be ignored if the .aspx file already has a MasterPageFile @ Page directive declared?
Baddie
Yes, you have to use View("ViewName", "MasterPageName"). I am not shure if the aspx cant have its own @Page directive.
Malcolm Frexner
I don't want to use View("ViewName", "MasterPageName"), I want the master page to be loaded from the view's @Page directive.
Baddie
+2  A: 

Your best bet to solve the problem is probably to create a custom VirtualPathProvider

erikkallen
Thanks this worked. I had my virtual path provider just replace any occurrence of "SomePlace" with "RealPlace" in all the necessary over-ridable methods (GetFile,FileExists,GetDirectory,DirectoryExists,CombineVirtualPaths)
Baddie