Razor 视图引擎学习

Razor 视图文件扩展名为 cshtml 或者 vbhtml , 现在主要讨论 cshtml。

@ 定义 Razor 语句

Name: @Model.Name

Time View Rendered: @Date.Time.ToShoarTimeString() @if (Model.Category == "Watersports") {

@Model.Category Splash!

}

@: 输出单行不是以 html 标记开头的, 并且要包含 html 标记的内容

@if (Model.Category == "Watersports") {
   @: Category: @Model.Category Splash!
}

<text></text> 输出多行包含 html 标记的内容

@if (Model.Category == "Watersports") {
   
   @: Category: @Model.Category Splash!
   
      Row, row, row your boat,
      Gently down the stream ...
   
}

@model 表示使用模型对象的类型

@model Razor.Models.Product

@{} 表示代码段

@{
   if (Model.Category == "Watersports") {
      @: Category: @Model.Category Splash!
   }
   if (Model.Price > 10) {
      
Pricey!
} }

使用布局页面

在 cshtml 文件的开头可以指定使用哪个布局页面, 例如:
@{
   Layout = "~/Views/Shared/_Layout.cshtml";
}
如果不指定 Layout 属性, Razor 引擎会检查 Views 目录下面的 _ViewStart.cshtml 文件, 这个页面指定了默认的布局页面。 如果不是用布局页面, 则需要在页面的开头添加声明如下: @{ Layout = null; } 以下划线 (_) 开头的视图文件不会返回给用户, 只能在服务端 cshtml 文件中进行引用。

@RenderBody() 渲染子视图

表示在此渲染子视图, 只能出现在布局页面中, 且只能出现一次。

@RenderPage 渲染另一个页面

表示在当前位置渲染另外一个页面。

@RenderSection(name, required) 渲染一个区域

表示在当前页面渲染一个区域, 区域名称在布局页面定义, required 表示该区域是否为可选的。

@region name {} 实现一个区域的内容

与布局页面的 @RenderSection 相对应, 实现布局页面的定义的区域。
posted @ 2011-12-11 17:33  张志敏  阅读(869)  评论(0编辑  收藏  举报