Turn from: http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/
I gave a presentation to another in Microsoft yesterday on ASP.net MVC and the Razor view engine and someone asked if There is a reference for the Razor syntax.
It turns out, there are a pretty good guide about Razor available, but it ' s focused on covering the basics of Web Programmi ng using Razor and inline pages and not just the Razor syntax.
So I thought it might is handy to write up a a really concise quick reference about the Razor syntax.
Syntax/sample |
Razor |
Web Forms equivalent (or remarks) |
Code Block |
@{
int x = 123;
String y = "because.";
} |
<%
int x = 123;
String y = "because.";
%>
|
Expression (Html encoded) |
<span> @model. Message</span> |
<span><%: Model. Message%></span> |
Expression (unencoded) |
<span>
@Html. Raw (model. Message)
</span> |
<span><%= model. Message%></span> |
Combining Text and markup |
@foreach (var item in items) {
<span> @item. Prop</span>
} |
<% foreach (var item in items) {%>
<span><%: item. Prop%></span>
<%}%> |
Mixing code and Plain text |
@if (foo) {
<text>plain text</text>
} |
<% if (foo) {%>
Plain Text
<%}%> |
Using Block |
@ using (Html.BeginForm ()) {
<input type= "text" value= "input Here" >
} |
<% using (Html.BeginForm ()) {%>
<input type= "text" value= "input Here" >
<%}%> |
Mixing code and plain Text (alternate) |
@if (foo) {
@:P Lain Text is @bar
} |
Same as above |
Email Addresses |
Hi philha@example.com |
Razor recognizes basic email format and are smart enough not to treat the @ as a code delimiter |
Explicit Expression |
<span>isbn@ (Isbnnumber) </span> |
In this case, we are explicit about the expression by using parentheses need. |
Escaping the @ sign |
<span>in Razor, use the
@ @foo to display the value of
foo</span> |
@@ renders a single @ in the response. |
Server side Comment |
@* This is
a server side
multiline Comment
*@ |
<%--This is
a server side
multiline Comment
--%> |
Calling generic method |
@ (myclass.mymethod<atype> ()) |
Use parentheses to being explicit about what the expression is. |
Creating a Razor Delegate |
@{func<dynamic, object> b = @<st
Rong> @item </strong>;
} @b ("Bold This") |
generates A&NBSP;FUNC<T, helperresult> that your can call from within |