C# Razor Syntax Quick Reference
C# Razor Syntax Quick Reference
Expression (Html
Encoded)
Expression (Unencoded)
Combining Text and
markup
Explicit Expression
Razor
@{
int x = 123;
string y = "because.";
int x = 123;
string y = "because.";
%>
<span>@model.Message</span>
<span><%: model.Message
%></span>
<span>
<span><%= model.Message
@Html.Raw(model.Message)
%></span>
</span>
@foreach(var item in items) { <% foreach(var item in
<span>@item.Prop</span>
items) { %>
}
<span><%: item.Prop
%></span>
<% } %>
@if (foo) {
<% if (foo) { %>
<text>Plain Text</text>
Plain Text
}
<% } %>
@if (foo) {
Same as above
@:Plain Text is @bar
}
Hi [email protected]
Razor recognizes basic email
<%--
Func<dynamic, object> b =
@<strong>@item</strong>;
}
@b("Bold this")
Hello @title. @name.
Conditional data-*
attributes.
data-* attributes are
always rendered.
Boolean attributes
<div data-x="@xpos"></div>
<input type="checkbox"
checked="@isChecked" />
<script
src="/myscript.js">
</script>
Notice in the mixing expressions and text example that Razor is smart enough to know that the
ending period is a literal text punctuation and not meant to indicate that its trying to call a
method or property of the expression.
Let me know if there are other examples you think should be placed in this guide. I hope you
find this helpful.
UPDATE 12/30/2012:Ive added a few new examples to the table of new additions to Razor
v2/ASP.NET MVC 4 syntax. Razor got a lot better in that release!