Sometimes my application has a section with normal ASP.NET requests that doesn't go through the ASP.NET MVC pipeline. I still want to integrate it with the ASP.NET MVC section of my app, using the same master page for example. The ViewMasterPage validates to make sure that the page being rendered is a ViewPage with the same type, so you can't use a normal page with a ViewMasterPage. If you run a ViewPage without an ASP.NET MVC context, all of the html helper methods will throw NullReferenceExceptions.

The solution to this issue is to make your page inherit from ViewPage, and then spoof the ASP.NET MVC context before the page renders. This will allow the page to work with a normal ASP.NET request (no ASP.NET MVC pipeline), but also use the same ViewMasterPage used for the rest of your site.

Here's what to do:

  • Make your page class inherit from ViewPage instead of Page.
  • Add the following method to your page:
    void SpoofMvc()
    {
    ControllerContext ctx = new ControllerContext();

    ctx.RouteData = new RouteData();

    ctx.HttpContext = new HttpContextWrapper(Context);
    ctx.RouteData.Values.Add("controller", "TightContent");
    ctx.RouteData.Values.Add("action", "View");

    this.Html = new HtmlHelper(new ViewContext(ctx, new WebFormView(this.Request.FilePath), ViewData, new TempDataDictionary(), Response.Output), this);
    }
  • Call the method before the page is rendered. Page_Load or Page_PreRender should work.