ASP.NET MVC View Engine Comparison
Asked Answered
J

6

342

I've been searching on SO & Google for a breakdown of the various View Engines available for ASP.NET MVC, but haven't found much more than simple high-level descriptions of what a view engine is.

I'm not necessarily looking for "best" or "fastest" but rather some real world comparisons of advantages / disadvantages of the major players (e.g. the default WebFormViewEngine, MvcContrib View Engines, etc.) for various situations. I think this would be really helpful in determining if switching from the default engine would be advantageous for a given project or development group.

Has anyone encountered such a comparison?

Jewry answered 20/9, 2009 at 15:47 Comment(0)
J
434

ASP.NET MVC View Engines (Community Wiki)

Since a comprehensive list does not appear to exist, let's start one here on SO. This can be of great value to the ASP.NET MVC community if people add their experience (esp. anyone who contributed to one of these). Anything implementing IViewEngine (e.g. VirtualPathProviderViewEngine) is fair game here. Just alphabetize new View Engines (leaving WebFormViewEngine and Razor at the top), and try to be objective in comparisons.


System.Web.Mvc.WebFormViewEngine

Design Goals:

A view engine that is used to render a Web Forms page to the response.

Pros:

  • ubiquitous since it ships with ASP.NET MVC
  • familiar experience for ASP.NET developers
  • IntelliSense
  • can choose any language with a CodeDom provider (e.g. C#, VB.NET, F#, Boo, Nemerle)
  • on-demand compilation or precompiled views

Cons:

  • usage is confused by existence of "classic ASP.NET" patterns which no longer apply in MVC (e.g. ViewState PostBack)
  • can contribute to anti-pattern of "tag soup"
  • code-block syntax and strong-typing can get in the way
  • IntelliSense enforces style not always appropriate for inline code blocks
  • can be noisy when designing simple templates

Example:

<%@ Control Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<% if(model.Any()) { %>
<ul>
    <% foreach(var p in model){%>
    <li><%=p.Name%></li>
    <%}%>
</ul>
<%}else{%>
    <p>No products available</p>
<%}%>

System.Web.Razor

Design Goals:

Pros:

  • Compact, Expressive, and Fluid
  • Easy to Learn
  • Is not a new language
  • Has great Intellisense
  • Unit Testable
  • Ubiquitous, ships with ASP.NET MVC

Cons:

  • Creates a slightly different problem from "tag soup" referenced above. Where the server tags actually provide structure around server and non-server code, Razor confuses HTML and server code, making pure HTML or JS development challenging (see Con Example #1) as you end up having to "escape" HTML and / or JavaScript tags under certain very common conditions.
  • Poor encapsulation+reuseability: It's impractical to call a razor template as if it were a normal method - in practice razor can call code but not vice versa, which can encourage mixing of code and presentation.
  • Syntax is very html-oriented; generating non-html content can be tricky. Despite this, razor's data model is essentially just string-concatenation, so syntax and nesting errors are neither statically nor dynamically detected, though VS.NET design-time help mitigates this somewhat. Maintainability and refactorability can suffer due to this.
  • No documented API, http://msdn.microsoft.com/en-us/library/system.web.razor.aspx

Con Example #1 (notice the placement of "string[]..."):

@{
    <h3>Team Members</h3> string[] teamMembers = {"Matt", "Joanne", "Robert"};
    foreach (var person in teamMembers)
    {
        <p>@person</p>
    }
}

Bellevue

Design goals:

  • 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

Brail

Design Goals:

The Brail view engine has been ported from MonoRail to work with the Microsoft ASP.NET MVC Framework. For an introduction to Brail, see the documentation on the Castle project website.

Pros:

  • modeled after "wrist-friendly python syntax"
  • On-demand compiled views (but no precompilation available)

Cons:

  • designed to be written in the language Boo

Example:

<html>    
<head>        
<title>${title}</title>
</head>    
<body>        
     <p>The following items are in the list:</p>  
     <ul><%for element in list:    output "<li>${element}</li>"%></ul>
     <p>I hope that you would like Brail</p>    
</body>
</html>

Hasic

Hasic uses VB.NET's XML literals instead of strings like most other view engines.

Pros:

  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular VB.NET code
  • Unit testable

Cons:

  • Performance: Builds the whole DOM before sending it to client.

Example:

Protected Overrides Function Body() As XElement
    Return _
    <body>
        <h1>Hello, World</h1>
    </body>
End Function

NDjango

Design Goals:

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

Pros:


NHaml

Design Goals:

.NET port of Rails Haml view engine. From the Haml website:

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 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.

Pros:

  • terse structure (i.e. D.R.Y.)
  • well indented
  • clear structure
  • C# Intellisense (for VS2008 without ReSharper)

Cons:

  • an abstraction from XHTML rather than leveraging familiarity of the markup
  • No Intellisense for VS2010

Example:

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

NVelocityViewEngine (MvcContrib)

Design Goals:

A view engine based upon NVelocity which is a .NET port of the popular Java project Velocity.

Pros:

  • easy to read/write
  • concise view code

Cons:

  • limited number of helper methods available on the view
  • does not automatically have Visual Studio integration (IntelliSense, compile-time checking of views, or refactoring)

Example:

#foreach ($p in $viewdata.Model)
#beforeall
    <ul>
#each
    <li>$p.Name</li>
#afterall
    </ul>
#nodata 
    <p>No products available</p>
#end

SharpTiles

Design Goals:

SharpTiles is a partial port of JSTL combined with concept behind the Tiles framework (as of Mile stone 1).

Pros:

  • familiar to Java developers
  • XML-style code blocks

Cons:

  • ...

Example:

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

Spark View Engine

Design Goals:

The idea is to allow the html to dominate the flow and the code to fit seamlessly.

Pros:

  • Produces more readable templates
  • C# Intellisense (for VS2008 without ReSharper)
  • SparkSense plug-in for VS2010 (works with ReSharper)
  • Provides a powerful Bindings feature to get rid of all code in your views and allows you to easily invent your own HTML tags

Cons:

  • No clear separation of template logic from literal markup (this can be mitigated by namespace prefixes)

Example:

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
    <li each="var p in products">${p.Name}</li>
</ul>
<else>
    <p>No products available</p>
</else>

<Form style="background-color:olive;">
    <Label For="username" />
    <TextBox For="username" />
    <ValidationMessage For="username" Message="Please type a valid username." />
</Form>

StringTemplate View Engine MVC

Design Goals:

  • Lightweight. No page classes are created.
  • Fast. Templates are written to the Response Output stream.
  • Cached. Templates are cached, but utilize a FileSystemWatcher to detect file changes.
  • Dynamic. Templates can be generated on the fly in code.
  • Flexible. Templates can be nested to any level.
  • In line with MVC principles. Promotes separation of UI and Business Logic. All data is created ahead of time, and passed down to the template.

Pros:

  • familiar to StringTemplate Java developers

Cons:

  • simplistic template syntax can interfere with intended output (e.g. jQuery conflict)

Wing Beats

Wing Beats is an internal DSL for creating XHTML. It is based on F# and includes an ASP.NET MVC view engine, but can also be used solely for its capability of creating XHTML.

Pros:

  • Compile-time checking of valid XML
  • Syntax colouring
  • Full intellisense
  • Compiled views
  • Extensibility using regular CLR classes, functions, etc
  • Seamless composability and manipulation since it's regular F# code
  • Unit testable

Cons:

  • You don't really write HTML but code that represents HTML in a DSL.

XsltViewEngine (MvcContrib)

Design Goals:

Builds views from familiar XSLT

Pros:

  • widely ubiquitous
  • familiar template language for XML developers
  • XML-based
  • time-tested
  • Syntax and element nesting errors can be statically detected.

Cons:

  • functional language style makes flow control difficult
  • XSLT 2.0 is (probably?) not supported. (XSLT 1.0 is much less practical).

Jewry answered 20/9, 2009 at 15:47 Comment(20)
Why on earth is NDjango using F# instead of IronPython? Seems like a lack of imagination around naming. Was it impossible to just port the Python version? I know IronPython has been able to run parts of Django for some time.Rheims
Good summary on the view engines.Katharinekatharsis
@ BrianLy: because F# is compiled and functional, which means it's fast, more interoperable with the rest of the runtime (at least until c# 4), and idempotent. we went down the ironpython route at first, but weren't happy with the results. as far as naming - we're open to suggestions :)Wulfenite
May I suggest we add a small sample code to each example? the sample should do the same thing in each engine, and include: output, condition, loopFletcherfletcherism
Sounds like a good idea. It's a community wiki, so feel free to start it off.Jewry
Down voting because of the Cons section of Brail. Having Boo as the language is certainly not a con.Wachter
@Owen: Yes it is. You have to look at this from the perspective of a C# developer. You don't want to learn yet another language just to use a templating engine. (naturally if you already know Boo, that's cool, but for the majority of C# developers, this is an addition hurdle to overcome)Cuneate
It should be updated to cover Razor ( weblogs.asp.net/scottgu/archive/2010/07/02/… )Cha
Razor is in there. It should be updated to alphabetize Razor.Jewry
I agree with Owen about Brail and Boo. View engines use very little actual code, you don't have to properly learn Boo as a language to use Brail, only loops, if, very basic stuff.Pitfall
I'd like to suggest too the onView View engine at : sourceforge.net/projects/onviewHolmun
@Hoghweed: please add it to the list, it's a wiki after all.Pitfall
Could someone add examples for all/most of these? I'm afraid that examples may push this answer past the poorly documented character limit for answers though :(Jutta
Boo is a Pro, not a Con. You are already "outside" C#, the terser the template can come the better. C# was not meant to be used in a "templating" context, it is somewhat expressive but not "wrist friendly". On the other hand, BOO was created with that in mind and as such it lends itself much better to be used in a templating context.Wop
But it is certainly an injustice to vote this answer down because of this single difference in opinion... Great answer!Wop
AFAIR with string template you can not write complex conditions like: if (a && b && !c) which is important to mention in Cons. See their ref: antlr.org/wiki/display/ST/StringTemplate+cheat+sheetMarlinmarline
@ChristianKlauser to be honest, templating language should be the choice of the frontend developer...Howze
It’s too bad that VB’s XML literals don’t support streaming (as far as I know). But, one mitigating factor is that since you’re mostly likely going to be using XSLT in order to have something like an ASP.NET master page, then you don’t have to create a full HTML DOM in memory; it’s enough to generate a minimal XML document that can transformed either on the server (which supports streaming), or on the client.Preraphaelite
It appears that most of the third party view engines have not been updated in quite a while or the links are no longer valid. Is Razor that good that dev work in this area has stopped?Beane
Does anyone still use .NET?Jewry
M
17

My current choice is Razor. It is very clean and easy to read and keeps the view pages very easy to maintain. There is also intellisense support which is really great. ALos, when used with web helpers it is really powerful too.

To provide a simple sample:

@Model namespace.model
<!Doctype html>
<html>
<head>
<title>Test Razor</title>
</head>
<body>
<ul class="mainList">
@foreach(var x in ViewData.model)
{
<li>@x.PropertyName</li>
}
</ul>
</body>

And there you have it. That is very clean and easy to read. Granted, that's a simple example but even on complex pages and forms it is still very easy to read and understand.

As for the cons? Well so far (I'm new to this) when using some of the helpers for forms there is a lack of support for adding a CSS class reference which is a little annoying.

Thanks Nathj07

Mcclinton answered 13/11, 2011 at 19:21 Comment(1)
Doh! Just noticed how old this discussion is. Oh well, maybe someone will find it and it will still prove useful.Mcclinton
K
10

I know this doesn't really answer your question, but different View Engines have different purposes. The Spark View Engine, for example, aims to rid your views of "tag soup" by trying to make everything fluent and readable.

Your best bet would be to just look at some implementations. If it looks appealing to the intent of your solution, try it out. You can mix and match view engines in MVC, so it shouldn't be an issue if you decide to not go with a specific engine.

Katharinekatharsis answered 20/9, 2009 at 15:49 Comment(1)
Thanks for the answer. I was literally starting what you suggested when I figured "someone has had to have done a summary already." I'm hoping for some aggregation of these types of design goals and shortcomings. "The Spark View Engine... aims to rid your views of "tag soup" by trying to make everything fluent and readable." That implies a reason for building it as well as a shortcoming of the default view engine. One more bullet in the list.Jewry
G
7

Check this SharpDOM . This is a c# 4.0 internal dsl for generating html and also asp.net mvc view engine.

Genova answered 30/4, 2010 at 21:10 Comment(3)
Sounds like the only reasonable way to build views.Spallation
can you add it to the general wiki'd answer?Pitfall
I can't find it on CodePlex or Google anymore. Where did it go?? (It's still on Codeproject: codeproject.com/Articles/667581/…)Reinforcement
C
5

I like ndjango. It is very easy to use and very flexible. You can easily extend view functionality with custom tags and filters. I think that "greatly tied to F#" is rather advantage than disadvantage.

Creath answered 25/2, 2010 at 19:48 Comment(0)
J
4

I think this list should also include samples of each view engine so users can get a flavour of each without having to visit every website.

Pictures say a thousand words and markup samples are like screenshots for view engines :) So here's one from my favourite Spark View Engine

<viewdata products="IEnumerable[[Product]]"/>
<ul if="products.Any()">
  <li each="var p in products">${p.Name}</li>
</ul>
<else>
  <p>No products available</p>
</else>
Jackpot answered 1/2, 2010 at 17:51 Comment(1)
looks too much like coldfusion. I'm not a big fan of mixing code into markup like this. It becomes difficult to maintain.Curd

© 2022 - 2024 — McMap. All rights reserved.