mvc Razor视图语法与Aspx视图语法对比

最近学习了mvc的Razor视图引擎,其语法与mvc的aspx视图引擎语法相似,不过也有区别,Razor看上去更简洁

总结了下如下:

语法名称

Razor 语法

Web Forms 等效语法

代码块(服务端)

@{ int x = 123; string y = "test."; }

<% int x = 123; string y = "test."%>

表达式

encode:<p>@model.Message</p>

no encode:<p@Html.Raw(model.Message) </p>

encode:<p><%:model.Message %></p>

no encode:<p><%= model.Message %></p>

 

结合文本和标记的循环

 

@foreach(var item in items) 

{ 

  <p>@item.Prop</p> 

}

 

<% foreach(var item in items)

 { %> 

  <p><%:item.Prop %></p>

 <% } %>

 

代码和文本混合

 

@if (foo) { <text>Plain Text</text> }

 

@if (foo) { @:Plain Text is @bar }

 

<% if (foo) { %> Plain Text <% } %>

 

服务器端注释

 

@* This is a server side multiline comment  *@

 

<%-- This is a server side multiline comment --%>

 

调用一个方法

 

@(MyClass.MyMethod<AType>())

使用括号来明确表达是什么.

 
 

混合表达式和文本

 

Hello @title. @name.

 

Hello <%: title %><%: name %>.

简单的总结了一些,看上去比aspx视图爽多了,嘿嘿

原文地址:https://www.cnblogs.com/DonnyPeng/p/3088574.html