”;
The View Engine in ASP.NET is used to translate our views to HTML and then render them to the browser. By default, ASP.Net supports ASPX and the Razor View Engine. The view engine templates have a different syntax than the implementation. In this chapter, we will discuss the two most important view engines which are −
-
ASPX View Engine also known as Web Form View Engine and
-
Razor View Engine
There are many more third-party view engines, like Spark, Nhaml, etc.
ASPX View Engine
ASPX or Web Form Engine is the default view engine for ASP.NET that is included with ASP.NET MVC from the beginning itself.
-
The syntax used for writing a view with the ASPX View Engine is the same as the syntax used in the ASP.NET web forms.
-
The file extensions are also the same as for ASP.NET web forms (like .aspx, .ascx, .master).
-
ASPX uses “<% = %>” or “<% : %>” to render server-side content.
-
The namespace for Webform Engine is System.Web.Mvc.WebFormViewEngine.
-
ASPX View Engine does nothing to avoid Cross-Site Scripting attacks by default.
-
ASPX View Engine is comparatively faster than Razor View Engine.
Razor View Engine
Razor Engine is an advanced view engine that was introduced with MVC3. It is not a new language, but it is a new markup syntax.
-
The Razor syntax is based on the C# programming language.
-
The Razor syntax also supports the Visual Basic language, and everything that we will do using C#, you can do all of that in Visual Basic as well.
-
The namespace for Razor Engine is System.Web.Razor.
-
Razor uses the “@” character instead of “<% %>” as used by the ASPX View Engine.
-
The Razor file extension is “cshtml” for the C# language.
-
By default, Razor View Engine encodes html tags or scripts before it’s being rendered to view that avoids Cross-Site Scripting attacks.
-
Razor View Engine is slow as compared to ASPX View Engine.
Syntax Differences
To understand the syntax difference, let’s have a look into a simple example that is written in both ASPX and Razor view engines. Following is the code snippet for ASPX view engine.
<%foreach (var student in Students){ %> <% if (student.IsPassed){ %> <% = student.FirstName%> is going to next grade. <% } else{ %> <% = student. FirstName %> is not going to next grade. <% } %> <% } %>
Following is the same example code written in Razor View engine.
@foreach (var student in Students){ @if(student.IsPassed){ @student. FirstName is going to next grade. } else { @student. FirstName is not going to next grade. } }
If you look at both the above code snippets written in ASPX and Razor syntax, then you can see quite clearly that Razor syntax is clean and simpler as compared to the ASPX syntax. One of the disadvantages of Razor is, it is not supported by visual editors like Dream Viewer.
”;