Using the Razor view engine with S#arp architecture

Whilst the Sharp Architecture maintainers have little interest in Razor (see here), I have been using it recently and like the syntax.

Swapping out a default project to use Razor instead of (or in addition to) the default engine isn’t too difficult.

Enabling the view engine

In Global.asax, find the few lines below in Application_Start():

ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new AreaViewEngine());

We need to register Razor here, by adding the line below:

ViewEngines.Engines.Add(new RazorViewEngine());

If you do not plan on using the default view engine then you can comment the existing line and remove all the .aspx files from the Views directory.

Configuring the default layout

Create an empty file called _ViewStart.cshtml in the root of your Views folder:

@{
Layout = "~/Views/Shared/_Layout.cshtml";
}

This code runs before any other view code in this directory or below and sets the default layout so you don’t have to set it manually in every view (see the MVC3 release notes for more information).

Create a basic template

Lastly we need the layout which was referenced above, created as Views/Shared/_Layout.cshtml. You could copy and paste this from a new MVC Razor application, which is what I did to end up with the template below:

<!DOCTYPE html>
<html>
<head>
    <title>MyApp - @ViewBag.Title</title>
    <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" />
    <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script>
</head>
<body>
    <div class="page">
        <div id="header">
            <div id="title">
                <h1>MyApp</h1>
            </div>

        </div>

        <div id="main">
            @RenderBody()
            <div id="footer">
            </div>
        </div>
    </div>
</body>
</html>

Conclusion

This is all that should be necessary to enable Razor and start to return basic views from your controllers. From here on you can create views just like in the MVC3 tutorials.

David Cannings
David Cannings
Cyber Security

My interests include computer security, digital electronics and writing tools to help analysis of cyber attacks.