转自:http://haacked.com/archive/2011/01/06/razor-syntax-quick-reference.aspx/
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) | | |
Expression (Unencoded) | | |
Combining Text and markup | | |
Mixing code and Plain text | | |
Using block | | |
Mixing code and plain text (alternate) | | Same as above |
Email Addresses | | Razor recognizes basic email format and is smart enough not to treat the @ as a code delimiter |
Explicit Expression | | In this case, we need to be explicit about the expression by using parentheses. |
Escaping the @ sign | | @@ renders a single @ in the response. |
Server side Comment | | |
Calling generic method | | Use parentheses to be explicit about what the expression is. |
Creating a Razor Delegate | | Generates a Func<T, HelperResult> that you can call from within Razor. See this blog post for more details. |
Mixing expressions and text | | |
NEW IN RAZOR v2.0/ASP.NET MVC 4 | ||
Conditional attributes | | When className = null When className = "" When className = "my-class" |
Conditional attributes with other literal values | | When className = null Notice the leading space in front of foo is removed. When className = "my-class" |
Conditional data-* attributes. data-* attributes are always rendered. | | When xpos = null or "" When xpos = "42" |
Boolean attributes | | When isChecked = true When isChecked = false |
URL Resolution with tilde | | When the app is at / When running in a virtual application named MyApp |
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 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.
UPDATE 12/30/2012:I’ve 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!
Also, if you want to know more, consider buying the Progamming ASP.NET MVC 4 book. Full disclosure, I'm one of the authors, but the other three authors are way better.