ASP.NET MVC 3及以上版本中,多了一种新的视图引擎——Razor。与原来的aspx视图比起有很多优点。下面详细说说Razor视图的基本语法。
1.代码和标签混合
aspx视图:
<ul id="products">
<% foreach(var p in products){ %>
<li><%=p.Name%> ($<%=p.Price%>)</li>
<% } %>
</ul>
相对于以上的aspx视图,Razor表示为:
<ul id="products">
@foreach(var p in products) {
<li>@p.Name ($@p.Price)</li>
}
</ul>
2.代码块
aspx视图:
<%
int x=123;
string y="because.";
%>
Razor视图:
@{
int x=123;
string y="beacuse.";
}
3.渲染输出
3.1 经过HTML编码。指变量中若有HTML元素,HTML元素以文本的形式输出。
aspx视图:
<span><%: model.Message %></span>
Razor视图:
<span>@model.Message</span>
3.2 未经过HTML编码。指变量中若有HTML元素,HTML元素会进行渲染。
<span><%= model.Message %></span>
Razor视图:
<span>@Html.Raw(model.Message)</span>
aspx视图:
<% if(foo) { %>
Plain Text
<% } %>
Razor视图(2种表示法,<text>标签是Razor中新增的标签,不会在HTML中渲染出来,它是说明<text>里面是一段纯文本):
@if(foo) {
<text>Plain Text</text>
}
或者:
@if(foo) {
@:Plain Text
}
aspx视图(变量后面的点,就是普通的点):
Hellow <%: title %>. <%: name %>.
Razor视图(变量后面的点,就是普通的点):
Hellow @title. @name.
diqiu@qq.com(因为@前面没有空格或截断)
7.@符号(两个连续的@@符号会被渲染为一个@符号)
<span>In Razor, you use the @@foo to display the value of foo</span>
当要渲染输出的代码@前无空格或标记位时,我们需要使用小括弧进行显式的渲染输出,小括弧里可以是变量、表达式......
<span>ISBN@(isbnNumber)</span>
aspx视图:
<%--This is not hear--%>
Razor视图:
@*This is not hear*@
对于动态方法返回值之类的输出我们使用小括弧将代码闭合起来即可
@(MyClass.MyMethod<AType>())
@{
Func<dynamic, object> b=@<stong>@item</strong>
}
@b("Blod this")
<ul>
@foreach(var p in products) {
<li>
@p.ProductName
@if(p.UnitsInStock==0) {
@:(Out of stock!)
}
else if(p.UnitsInStock<4) {
@:(Only @p.UnitsInStock left!)
}
</li>
}
</ul>
13.多行内容混合代码
外面有标签,会自动换行:
@if(p.UnitsInStock==0){
<p>
Line one of content
Line two of content
Date is: @DateTime.Now
Line four of content
</p>
}
内容外部没有html标记包装时:
@if(p.UnitsInStock==0){
@: Line one of content
@: Line two of content
@: Line three of content
}
或者:
@if(p.UnitsInStock==0){
<text>
This is a book of center
Hellow Toney mannj
nuggest is: @DateTime.Now
Isn't that neat?
</text>
}
详细参考:http://edu.51cto.com/lesson/id-14584.html