1

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
Omar
  • 39,496
  • 45
  • 145
  • 213

2 Answers2

2

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

erikkallen
  • 33,800
  • 13
  • 85
  • 120
  • 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) – Omar Dec 01 '09 at 17:16
-1

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

public CustomViewEngine()
{
    MasterLocationFormats = new string[] {
        "~/RealPlace/Site.Master""
    };
}
Mathias F
  • 15,906
  • 22
  • 89
  • 159
  • 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? – Omar Nov 25 '09 at 23:46
  • Yes, you have to use View("ViewName", "MasterPageName"). I am not shure if the aspx cant have its own @Page directive. – Mathias F Nov 26 '09 at 09:15
  • I don't want to use View("ViewName", "MasterPageName"), I want the master page to be loaded from the view's @Page directive. – Omar Nov 26 '09 at 21:25