语法/示例 | Razor | Web Forms对应写法或说明 |
---|---|---|
代码块 |
@{ int x = 123; string y = "because."; } |
<% int x = 123; string y = "because."; %> |
表达式(Html Encoded) |
<span>@model.Message</span> |
<span><%: model.Message %></span> |
表达式(Unencoded) |
<span> @Html.Raw(model.Message) </span> |
<span><%= model.Message %></span> |
组合文本和标记 |
@foreach(var item in items) { <span>@item.Prop</span> } |
<% foreach(var item in items) { %> <span><%: item.Prop %></span> <% } %> |
混合代码和纯文本 |
@if (foo) { <text>Plain Text</text> } |
<% if (foo) { %> Plain Text <% } %> |
混合代码和纯文本 (备选) |
@if (foo) { @:Plain Text is @bar } |
同上 |
电子邮件地址 |
Hi philha@example.com |
Razor 能认出基本的电子邮件格式,不会把 @ 当作代码分界符 |
显式表达式 |
<span>ISBN@(isbnNumber)</span> |
这种情况下,需要对表达式使用圆括号 |
取消转义 @ 符号 |
<span>In Razor, you use the @@foo to display the value of foo</span> |
@@ 表示 @ |
混合表达式和文本 |
Hello @title. @name. |
Hello <%: title %>. <%: name %>. |
服务器端注释 |
@* This is a server side multiline comment *@ |
<%-- This is a server side multiline comment --%> |