Thursday, May 24, 2012

Rock out with Razor

The first glimpse we had at the Razor view engine was seen in the release of MVC 3 and the first thing anyone will notice is how easy programming becomes on a simple HTML page or rather CSHTML which is the Razor view extension.

The Razor syntax is template markup syntax, based on the C# programming language that enables the developer to use an HTML construction workflow. Instead of using the ASP.NET .ASPX markup syntax with <%= %> symbols to indicate code blocks, Razor syntax starts code blocks with an @ character and doesn’t require explicit closing of the code-block.

The idea behind Razor is to provide an optimized syntax for HTML generation using a code-focused templating approach, with minimal transition between HTML and code. The design reduces the number of characters and keystrokes, and enables a more fluid coding workflow .

In Razor V1 code similar to this is used
<div id=”thisdiv” class=”@someclass”>

If the value of someclass was to be null the rendered code would be

<div id=”thisdiv” class=””>

This is mainly due to the fact that Razor V1 sees NULL items as empty strings and I believe most people would agree that the rendered code looks horrific to say the least. However in Razor V2 the rendered code is a lot cleaner, this is how Razor V2 would render the same code

<div id=”thisdiv”>

As you can see the class attribute is now entirely missing, making the code appear a lot cleaner. By rendering values in this manner, it also accounts for a flaw in the previous Razor engine because of the difference between a NULL and a String.Empty attribute which has a length value of 0 and NULL of course being the complete absence of a value.

Razor combines simplicity and elegance into an easily readable HTML format and calling functions or objects to a View is easier than ever seen before in a view engine. What makes Razor an even better contender for broad spectrum application development is the fact that it ships out with MVC, which has superb cross browser compatibility and also gives you an option to bind Jquery UI’s etc. to a web application that will even run with the dinosaurs in Internet Explorer 7.

By: Stefan Jonck
For more detailed examples and descriptions on the Razor View Engine visit:

No comments:

Post a Comment