I gave a presentation to another team at Microsoft yesterday on ASP.NET MVC and the Razor view engine and someone asked if there was a reference for the Razor syntax.
It turns out, there is a pretty good guide about Razor available, but it’s focused on covering the basics of web programming using Razor and inline pages and not just the Razor syntax.
So I thought it might be handy to write up a a really concise quick reference about the Razor syntax.
Syntax/Sample | Razor | Web Forms Equivalent (or remarks) |
---|---|---|
Code Block | @{ | <% |
Expression (Html Encoded) | <span>@model.Message</span> | <span><%: model.Message %></span> |
Expression (Unencoded) | <span> | <span><%= model.Message %></span> |
Combining Text and markup | @foreach(var item in items) { | <% foreach(var item in items) { %> |
Mixing code and Plain text | @if (foo) { | <% if (foo) { %> |
Mixing code and plain text (alternate) | @if (foo) { | Same as above |
Email Addresses | Hi philha@example.com | Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter |
Explicit Expression | <span>ISBN@(isbnNumber)</span> | In this case, we need to be explicit about the expression by using parentheses. |
Escaping the @ sign | <span>In Razor, you use the | @@ renders a single @ in the response. |
Server side Comment | @* | <%-- |
Mixing expressions and text | Hello @title. @name. | Hello <%: title %>. <%: name %>. |
Notice in the last example that Razor is smart enough to know that the ending period is a literal text punctuation and not meant to indicate that it’s 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.
Tidak ada komentar:
Posting Komentar