SLaks.Blog

Making the world a better place, one line of code at a time

Dissecting Razor, part 3: Razor and MVC

Posted on Thursday, February 03, 2011, at 6:49:00 PM UTC

Last time, we saw how standalone Razor pages are served.

MVC3 maintains the strict separation between the WebPages framework and the Razor engine.1

Razor Side

Like the WebPages framework, MVC3 interacts with Razor indirectly, by relying on RazorBuildProvider from System.Web.WebPages.Razor.dll.   However, MVC3 requires that Razor views inherit its own base class, System.Web.Mvc.WebViewPage.

MVC3 adds a new @model directive, which can be used instead of @inherits to specify a strongly-typed model.  This syntax is implemented by customized RazorCodeParsers and RazorCodeLanguages in the System.Web.MVC.Razor namespaces.  These classes are invoked by MvcRazorEngineHosts from a custom RazorHostFactory registered in Views/Web.Config:

<system.web.webPages.razor>
    <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
        <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
        </namespaces>
    </pages>
</system.web.webPages.razor>

MVC Side

On the MVC side, MVC3 includes a new RazorViewEngine which creates RazorView instances.  RazorView inherits the existing BuildManagerCompiledView class, which passes the view’s virtual path to the build manager.  RazorView will take the WebViewPage from the build manager, find any matching start pages, and execute the view.

As with the WebPages framework, one can substitute other templating engines.  One can register a build provider which compiles classes that inherit WebViewPage, then add a RazorViewEngine to ViewEngines.Engines with additional extensions in its FileExtensions property.

Next time: Inside Razor Pages

Categories: Razor, ASP.Net, dissecting-razor, .Net, ASP.Net MVC Tweet this post

comments powered by Disqus