MVC Razor 语法(转)

http://blog.csdn.net/pasic/article/details/7072340

语法名称Razor 语法Web Forms 等效语法
代码块
 @{ int x = 123; string y = "because."; } 
 <% int x = 123; string y = "because."; %> 
表达式(默认encode)
 <span>@model.Message</span> 
 <span><%: model.Message %></span> 
表达式(不encode)
 <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 } 
同上
Email 地址
 Hi philha@example.com
Razor 认识基本的邮件格式.可智能识别.
显示表达式
 <span>ISBN@(isbnNumber)</span> 
在括号里可以有些简单的操作.扩展一下就是@(20*pageIndex) 输出运算结果
 输出@符号 
 <span>In Razor, you use the @@foo to display the value of foo</span> 
要显示@符号,用两个@符号"@@"表示.
服务器端注释
 @* This is a server side multiline comment  *@ 
 <%-- This is a server side multiline comment --%> 
调用一个方法
 @(MyClass.MyMethod<AType>()) 
使用括号来明确表达是什么.
创建一个Razor委托
 @{ Func<dynamic, object> b = @<strong>@item</strong>; } @b("Bold this")
更多信息查看 this blog post .
混合表达式和文本
 Hello @title. @name.
 Hello <%: title %>. <%: name %>.

希望对您有所帮助. 

补充一个在View的脚本Script中显示JSON对象的方法

需求:var data=[{id:1,title="标题1},{id:2,title="标题2"}] 

实现:var data=@Html.Raw(@Newtonsoft.Json.JavaScriptConvert.SerializeObject(Model)) 

用Json.Net转换一下再Raw输出即可

原文地址:https://www.cnblogs.com/mmcmmc/p/3834187.html