Getting Started with Razor

Razor is one of my favorite ways to write server-side views. I love it so much I switched my Wordpress blog to this shiny new Razor WebPages site. It is hands down my favorite way to mix server view code with HTML. It allows you to separate content from layout in an easy to understand format. Razor also allows you to leverage existing C# to create dynamic webpages. Here is a simple example of Razor:

Sample layout page (_Layout.cshtml)


Sample blog entry (my-blog-post.cshtml)

        Layout = "_Layout.cshtml"
        Page.Title = "My blog entry";
        Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vestibulum quis elit eros.
        Vestibulum sollicitudin ipsum nec nunc commodo, vel tempus mi tempus. Nulla malesuada porttitor mauris ut accumsan.
        Duis commodo turpis mauris, in bibendum est imperdiet auctor. Nulla facilisis risus at lobortis pellentesque.
        Morbi accumsan ex ut sollicitudin condimentum. Nam sagittis lobortis dui, quis sodales ligula elementum vitae.
        Praesent euismod ipsum nec magna volutpat, in cursus urna ultrices. Sed vehicula a dolor mattis gravida.
        Quisque egestas tortor leo, non aliquet tellus aliquam eu. Phasellus varius dictum libero, in tristique sapien sodales cursus.
        Aenean lobortis sagittis augue, in sollicitudin libero gravida id. Proin viverra maximus massa a venenatis.
        In auctor nulla sed nunc laoreet lacinia. Sed a turpis ex.
        Suspendisse sodales efficitur tempor. Vivamus quis dui arcu.
        Pellentesque neque orci, lobortis quis ultrices sed, pharetra sit amet massa.
        Ut diam leo, mattis ut dolor eu, euismod congue magna. Donec condimentum lorem sed quam dapibus ornare.
        Mauris non pellentesque libero, non dictum dui. Sed eu molestie mi, vitae porttitor mauris.

What does that do?

_Layout.csthml defines a general template for an html page. It expects the Page property to have a Title, so it can use it as the html title. Page is a dynamic object that acts as a dictionary. You can also use PageData["Title"] if dynamic typing in C# weirds you out. The @RenderBody() in the body of the html tells the layout where to put the contents of the page. It is required when using a .cshtml page as a layout file.

my-blog-post.cshtml has the unique contents of the page. The section surrounded by @{ } is a code block that first tells Razor to use _Layout.cshtml for general layout, and then tells Razor what Page.Title should be. The rest of the page has the contents of the page itself.

Note: When using ASP.NET MVC, Page and PageData are ViewBag and ViewData respectively

What does that do for me?

Having this kind of a layout system keeps everything separated by responsibility and encourages reduction of HTML code. It has made my web development easier for certain.