返璞歸真 asp.net mvc (9) - asp.net mvc 3.0 新特性之 View(Razor)
返璞歸真 asp.net mvc (9) - asp.net mvc 3.0 新特性之 View(Razor)
作者:webabcd
介紹
asp.net mvc 之 asp.net mvc 3.0 新特性之 View(Razor):
- Razor 的語法
- Razor 與 Model
- Razor 與布局
示例
1、Razor 概述
RazorDemoController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVC30.Models; namespace MVC30.Controllers { public class RazorDemoController : Controller { public ActionResult Summary() { return View(); } } }
Summary.cshtml
@{ ViewBag.Title = "Razor 概述"; } <p> 使用 Razor 之前,要在 Web.Config 中做如下配置 <br /> <textarea rows="20" style="width: 100%"> <configSections> <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"> <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" /> </sectionGroup> </configSections> <system.web.webPages.razor> <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" /> <pages pageBaseType="System.Web.Mvc.WebViewPage"> <namespaces> <add namespace="System.Web.Mvc" /> <add namespace="System.Web.Mvc.Ajax" /> <add namespace="System.Web.Mvc.Html" /> <add namespace="System.Web.Routing" /> </namespaces> </pages> </system.web.webPages.razor> </textarea> </p> <p> View 在每次 Render 之前都會先執行 _ViewStart.cshtml 中的代碼 </p>
2、Razor 語法簡介
RazorDemoController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVC30.Models; namespace MVC30.Controllers { public class RazorDemoController : Controller { public ActionResult Syntax() { return View(); } } }
Syntax.cshtml
@{ ViewBag.Title = "Razor 語法"; } <p> 使用@符號加{},直接在 html 頁面中寫 C# <br /> @{ var currentTime = DateTime.Now; } @* 相當于 <% Htmlvar currentTime = DateTime.Now; %> *@ @currentTime.ToString("yyyy-MM-dd") </p> <p> 使用@符號,直接在 html 頁面中寫 C# 并輸出結果 <br /> 當前 URL: @Request.Url @* 相當于 <%= Request.Url %> *@ <br /> 當前 URL: @{ @Request.Url; } </p> <p> 想輸出字符@怎么辦?,那就@@ <br /> webabcd@@abc.com </p> <p> 在 Razor 中寫服務端注釋(客戶端不可見) @* code *@ </p> <p> Razor 自帶的類型轉換方法 <br /> 例:AsInt(), IsInt(), AsBool(), IsBool(), AsFloat(), IsFloat(), AsDecimal(), IsDecimal(), AsDateTime(), IsDateTime() <br /> 類似 AsInt() 的方法會有一個重載方法 AsInt(int defaultValue),用于當轉換失敗時返回指定的默認值 @{ var tmp = "2/14/1980"; var date = tmp.AsDateTime(); } @date.ToString("yyyy-MM-dd") </p> <p> 輸出文本的方法 <br /> @* <text></text> 或者 @: *@ @{ <text>我是文本</text> <br /> @:我是文本 } </p> <p> 獲取文件的 URL 絕對路徑的方法,一般用于 img 標簽,link 標簽,a 標簽中所引用的文件的完全 url 路徑 <br /> <img alt="" src="@Href("~/Content/themes/base/images/ui-icons_888888_256x240.png")" /> </p> <p> Html Helper, Ajax Helper, Url Helper 依然可以使用 <br /> @Html.TextBox("txt", "我是 TextBox") </p>
3、Razor 的與 Model 相關的 Demo
User.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace MVC30.Models { public class User { public int ID { get; set; } public string Name { get; set; } public string Password { get; set; } public string ConfirmPassword { get; set; } public DateTime DateOfBirth { get; set; } public string Comment { get; set; } } }
RazorDemoController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVC30.Models; namespace MVC30.Controllers { public class RazorDemoController : Controller { // 用于演示 View 如何獲取數據 public ActionResult Model() { // ViewBag 的本質就是把 ViewData 包裝成為 dynamic 類型 ViewBag.Author = "webabcd"; var list = new List<User>() { new User { ID = 1, Name = "webabcd", DateOfBirth = new DateTime(1980, 2, 14), Comment = "<b>mvp</b>" }, new User { ID = 2, Name = "prettygyy", DateOfBirth = new DateTime(1981, 6, 26), Comment = "<b>mvp</b>" } }; return View(list); } } }
_MyLayout_ParitalView.cshtml
@* 通過 @model 指定 Model 的類型,同時 Model 對象就是 Html.Partial() 或 Html.RenderPartial() 時傳遞過來的對象 *@ @using MVC30.Models; @model User <li>@Model.Name</li>
Model.cshtml
@* 通過 @using 引入命名空間 通過 @model 指定 Model 的類型,同時 Model 對象就是 Action 返回的數據 *@ @using MVC30.Models; @model List<User> @{ ViewBag.Title = "Razor 的與 Model 相關的 Demo"; } <p> <!-- 演示 ViewBag 的用法 --> Author: @ViewBag.Author </p> <div> <ul> <!-- Model 就是 Action 返回的數據 --> @foreach (var user in Model) { if (@user.Name == "webabcd") { <!-- 默認輸出的是經過 HTML 編碼后的數據,如果需要輸出原始數據則使用 Html.Raw() --> <li>@user.Name (@Html.Raw(@user.Comment))</li> } else { <li>@user.Name (@user.Comment)</li> } } </ul> </div> <!-- Html.Partial 與 Html.RenderPartial 的區別: Html.Partial - 直接將 View 的結果作為一個字符串輸出 Html.RenderPartial - 將 View 作為一個用戶控件嵌入到當前的 HttpContext 中 Html.Action 與 Html.RenderAction 的區別(演示參見 ControllerDemo/ChildActionOnlyDemo.cshtml): Html.Action - 直接將 Action 的結果作為一個字符串輸出 Html.RenderAction - 將 Action 作為一個用戶控件嵌入到當前的 HttpContext 中 Html.Partial, Html.RenderPartial 與 Html.Action, Html.RenderAction 的區別: 二者都需要指定 View,前者的 View 不需要 Action,而后者的 View 必須要有 Action --> <div> <ul> @foreach (var user in Model) { @Html.Partial("_MyLayout_ParitalView", user) @* <%= Html.Partial("_MyLayout_ParitalView", user) %> *@ } </ul> </div> <div> <ul> @{ var firstUser = Model.First(); Html.RenderPartial("_MyLayout_ParitalView", firstUser); @* <% Html.RenderPartial("_MyLayout_ParitalView", firstUser); %> *@ } </ul> </div>
4、Razor 的與布局相關的 Demo
RazorDemoController.cs
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using MVC30.Models; namespace MVC30.Controllers { public class RazorDemoController : Controller { public ActionResult LayoutView() { return View(); } } }
_ViewStart.cshtml
@{
// View 在每次 Render 之前都會先執行 _ViewStart.cshtml 中的代碼
Layout = "~/Views/Shared/_Layout.cshtml";
}
_Layout.cshtml
<!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> <!-- Url.Content() - 將指定的相對路徑轉換為絕對路徑 --> <link href="@Url.Content("~/Content/Site.css")" rel="stylesheet" type="text/css" /> <script src="@Url.Content("~/Scripts/jquery-1.4.4.min.js")" type="text/javascript"></script> </head> <body> @RenderBody() </body> </html>
_MyLayout_MasterPage.cshtml
<!DOCTYPE html> <html> <head> <title>@ViewBag.Title</title> </head> <body> <div style="background-color: Gray"> <!-- 引用此 Layout 的頁上的未指明 Section 的內容會在此 Render --> @RenderBody() </div> @if (IsSectionDefined("mySection")) { // 引用此 Layout 的頁后,如果指定名為 mySection 的 Section 的話,其會在此處 Render // 第二個參數的意思是,引用此 Layout 的頁是否必須有名為 mySection 的 Section @RenderSection("mySection", false) } else { @:沒有 mySection } </body> </html>
_MyLayout_RenderPage.cshtml
<h1> RenderPage <br /> @{ // 獲取 RenderPage() 傳遞過來的參數 if (@PageData["param"] == "abc") { @:param == "abc" } if (@PageData["param2"] == "xyz") { @:param == "xyz" } } </h1>
LayoutView.cshtml
@{ // 指定一個 Layout 頁(相當于母版頁) Layout = "_MyLayout_MasterPage.cshtml"; ViewBag.Title = "Razor 的與布局相關的 Demo"; } <!-- 在 Layout 中的 RenderBody() 中顯示 RenderPage() 的第二個參數的意思:給 _MyLayout_RenderPage.cshtml 傳遞參數 --> 在 RenderBody() 中顯示的內容 @RenderPage("~/Views/RazorDemo/_MyLayout_RenderPage.cshtml", new { param = "abc", param2 = "xyz"}) <!-- 在 Layout 中的 RenderSection("mySection") 中顯示 --> @section mySection { <b>My Section</b> }
5、其他
<p> Razor 的 dll 在這里 C:\Program Files\Microsoft ASP.NET\ASP.NET Web Pages\v1.0\Assemblies </p> <p> Razor 中約定:布局 View 或者需要被別的 View 引用的 View 要以“_”開頭 </p> <p> asp.net mvc 3.0 的 T4 模板的位置在 D:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\ItemTemplates\CSharp\Web\MVC 3\CodeTemplates <br /> 如果不想修改默認模板的話,那么就將模板安裝到當前項目中,然后只修改當前項目的 T4 模板,方法如下: <br /> Tools -> Library Package Manager -> Package Manager Console,然后輸入 install-package mvc3codetemplatescsharp,之后 CodeTemplates 文件夾就會添加到當前項目中 </p> <p> 新增的 HTML Helper,例如:Chart, WebGrid, WebImage, WebMail, Crypto 等,詳見 System.Web.Helpers.dll </p>
OK
[源碼下載]
浙公網安備 33010602011771號