Click here to Skip to main content
Click here to Skip to main content

ASP.NET MVC - Basic overview of different view engines

, 1 Oct 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
ASP.NET MVC - Basic overview of different View Engines (Razor, ASPX, Spark, NHaml, NDjango, Hasic, Brail, Bellevue, Sharp Tiles, String Template, Wing Beats, SharpDOM etc..)

ASP.NET MVC View Engines - Shemeer

Introduction

One of the best thing about ASP.NET MVC is its capability to change the default view engine with a Microsoft or a 3rd-party one. In this article, I will list down some of the available view engines for MVC.

What is a View Engine

View Engines are responsible for rendering the HTML from your views to the browser. The view engine template will have different syntax for implementation. Currently there are few number of view engines available for MVC and the top four view engines are Razor, traditional ASPX, Spark and NHaml.

If you really want then you can use multiple view engines in parallel in ASP.NET MVC.

In this article we will do a basic go through with some of the view engines.

Note: All view engines may not support all versions of ASP.NET MVC. Please check the corresponding sites to get the latest updates.

Razor

The Razor view engine is an advanced view engine from Microsoft, packaged with MVC 3. Razor using an @ character instead of aspx's <% %> and Razor does not require you to explicitly close the code-block, this view engine is parsed intelligently by the run-time to determine what is a presentation element and what is a code element.

In my opinion Razor is the best view engine available for MVC as its much cleaner and easy to write and read. This view engine is compatible with unit testing frameworks. It is very difficult to implement unit test with ASPX view engine. And other view engines doesn't provide anything related to testablity in their respective sites.

This is the default view engine in MVC 3 and MVC 4. Web pages with Razor syntax have the special file extension cshtml (Razor with C#) or vbhtml (Razor with VB).

Sample code is given below,

<h1>Sample with Razor</h1>
<h3>
    Hello @name, the year is @DateTime.Now.Year
</h3>
<p>
    checkout <a href="/Products/Details/@produtid">this prodcut</a>
</p>

Read more...

ASPX

The syntax for writing views with this engine is the same syntax that the ASP.NET Web Forms uses and the file extensions are also taken from ASP.NET Web Form (.aspx, .ascx, .master) . The coding will give us the memory of legacy ASP style.

This is the default view engine for MVC 1 and MVC 2.

Sample code is given below,

<h1>Sample with ASPX </h1>
<h3>
    Hello <%=name %>, the year is <%= DateTime.Now.Year %>
</h3>
<p>
    checkout <a href="/Products/Details/<%=produtid %>">this prodcut</a>
</p>

Read more...

Spark

This is an open-source view engine for ASP.NET MVC and Castle Project MonoRail frameworks. The idea is to allow the html to dominate the flow and the code to fit seamlessly.

Sample code is given below,

<h1>Sample with Spark</h1>
<ul>  
   <li each='var p in ViewData.Model.Products'>
    ${p.Name} !{Html.ActionLink[[ProductController]](c=>c.Edit(p.Id), "Edit")}
  </li>  
</ul>

Spark is from the MVCContrib library and this library totally contains 8 alternate view engines. Brail, NDjango, NHaml, NVelocity, SharpTiles, Spark, StringTemplate and XSLT.

Read more...

NHaml

"Haml is a markup language that‘s used to cleanly and simply describe the XHTML of any web document, without the use of inline code. Haml functions as a replacement for inline page templating systems such as PHP, ERB, and ASP. However, Haml avoids the need for explicitly coding XHTML into the template, because it is actually an abstract description of the XHTML, with some code to generate dynamic content." from the Haml website.

Sample code is given below,

@type=IEnumerable<Product>
- if(model.Any())
  %ul
    - foreach (var p in model)
      %li= p.Name
- else
  %p No products available

Read more...

NDjango

NDjango is an implementation of the Django Template Language on the .NET platform, using the F# language

Sample code,

{% block MainContent %}
<h2>
    {{ Message }}

Read More...

Hasic

Hasic uses VB.NET's XML literals instead of strings like most other view engines. Sample code is given below,

<h2>Sample with Hasic</h2>
<%= Model.Message.AsForm(Function(m) _
  <form method="post" action="/home/messages">
    <%= m.Sender.Label("Enter your name") %>
    <%= m.Text.TextArea().Label("Enter your message") %>
    <button type="submit">Send</button>
  </form>) %>

Read More...

Brail

The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework.

<h2>Sample with Brail</h2>
<div>
 ${childOutput}
</div>

Read More...

Bellevue

In this view engine the data binding code (Bellevue code) is separated from HTML.

The design goals of Bellevue are:

  • Respect HTML as first-class language as opposed to treating it as "just text".
  • Don't mess with my HTML! The data binding code (Bellevue code) should be separate from HTML
  • Enforce strict Model-View separation as described by Terence Parr here.

Read More...

SharpTiles

SharpTiles is a template engine built for the ASP.NET MVC and Monorail framework . It can also be used as a stand-alone template engine or as a servlet tag in ASP.NET WebForm pages. SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).

Sample code is given below,

<c:if test="${not fn:empty(Page.Tiles)}">
  <p class="note">
    <fmt:message key="page.tilesSupport"/>
  </p>
</c:if>

Read More...

String Template

An alternate, lightweight view engine for the ASP.NET MVC framework, built on top of the popular StringTemplate engine.

Read More...

Wing Beats

Wing Beats 0.9 is an internal little language (DSL) for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for it's capability of creating XHTML.

Below given is a sample code,

module MyProject.Views.Home
open WingBeats.Xhtml
open WingBeats.Xml
let e = XhtmlElement()
/// A template with the placeholders "title" and "content"
let masterTemplate =
    e.Html [
        { Name = "lang"; NS = {Prefix = "xml"; Uri = "http://www.w3.org/XML/1998/namespace"} }, "en"
        { Name = "lang"; NS = {Prefix = ""   ; Uri = "http://www.w3.org/1999/xhtml"        } }, "en"
    ] [
        e.Head [ 
            e.Title [ +"title" ]
            e.Link "[ type=text/css; rel=stylesheet; href=/styles/main.css ]"
            e.Script "[ type=text/javascript; src=/scripts/main.js ]" []
        ]
        e.Body [
            e.Div "#page" [
                e.H1 [ +"title" ]
                +"content"
            ]
        ]
    ]    
/// A view method. The result is sent to the view engine, where the
/// content is added to the template
let Index (model : string * string) = 
    let title, content = model
    masterTemplate, [ 
      "title"  , fun () -> &title
      "content", fun () -> e.Div "#content" & content
    ]

Read More...

SharpDOM

SharpDOM is a view engine for ASP.NET MVC platform allowing developers to design HTML layouts using C# 3.5/4.0. It is also generic internal DSL for generating HTML that can be used outside of MVC framework.

Below given is a sample code,

form.attr(action:Url.Action("LogOn"), method: Method.post)
[
    Html.ValidationSummary(true, "Login was unsuccessful. Please correct the errors and try again.").ToLiteral(),
    div[
        fieldset
        [
            legend["Account Information"],
            div.attr(@class: "editor-field")
            [
                Html.LabelFor(m => m.LogOnModel.UserName).ToLiteral(),
                Html.TextBoxFor(m => m.LogOnModel.UserName).ToLiteral(),
                Html.ValidationMessageFor(m => m.LogOnModel.UserName).ToLiteral()
            ],
            p[ input.attr(type: InputType.submit, value:"Log On") ]
        ]
    ]
]

Read More...

References

Most of the descriptions and codes are taken from the respective sites. Apart from the URLs mentioned in Read More links, the below given URL provides a very good comparison among this.

Summary

In this article I have listed some of the available view engines for ASP.NET MVC and also I have given all the respective site URLs in the corresponding sections so that you can easily check for the compatibility and latest updates.

I have put my time and efforts on all of my articles, please don't forget to mark your votes, suggestions and feedback to improve the quality of this and upcoming articles.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Shemeer NS
Software Developer (Senior)
India India
Technology Specialist | CodeProject MVP | Visual Studio Gallery Contributor | Author | Geek | Netizen | Husband | ChessPlayer
 
Most of my articles are listed on top 5 of the respective 'Best articles of the month' and some of my articles are published on ASP.NET WebSite's Article of the Day section.
 
Check my contributions in Visual Studio Gallery and Code Project
 
Technical Blog: http://www.shemeerns.com
Facebook: http://facebook.com/shemeernsblog
Twitter : http://twitter.com/shemeerns
Google+ : http://google.com/+Shemeernsblog
Follow on   Twitter   Google+

Comments and Discussions

 
GeneralMy vote of 4 PinmemberGregoryW4-Oct-12 5:32 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Mobile
Web03 | 2.8.141022.2 | Last Updated 1 Oct 2012
Article Copyright 2012 by Shemeer NS
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid