When I wrote my last article about MVC 3, the product was still in the "almost released" category of software. But now it is out in the wild in final form, and it's time to dive into more details of the Razor syntax. If you haven't already fired up Microsoft's Web Platform Installer and installed MVC 3, go get it! It is a great upgrade to the software.
I'm going to explore some of the syntax differences between views created with the ASP.NET Web Forms engine and the Razor view engine, along with some Razor-specific features. The ones I'll cover here are those that Web Forms developers will see most often, along with some that are just plain interesting.
Syntax Differences
Probably the first thing you'll notice is that a Web Forms view is defined in a file with an .aspx extension long used for Web Forms, such as LogOn.aspx. The Razor view is defined in LogOn.cshtml or LogOn.vbhtml, with a custom Razor file extension that indicates the language used in the view.
A Web Form page has a Page directive at the top that identifies the language used in the page, the master page file, and the type of model object used in the view:
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<DogApp.Models.LogOnModel>" %>
Or, for VB:
<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage(Of DogApp.LogOnModel)" %>
The Razor page has only a @model (C#) or @ModelType (VB) directive to identify the type of model object, as shown below. It figures out the language from the file extension and the master page is defined elsewhere, using a new feature, layout pages.
C#:
@model MVC3Dogs.Models.LogOnModel
VB:
@ModelType MVC3Dogs.LogOnModel
If you prefer the full syntax of specifying that the WebViewPage object is of a specific type, like in the Web Forms engine, you can use the @inherits statement at the top of the view instead of @model or @ModelType. There really is no reason to use @inherits, particularly since it is a syntax that Microsoft introduced with a preview version of MVC 3. This puts it in the awkward position of providing backward compatibility with a feature introduced in a pre-beta release.