ASP.NET MVC的Razor引擎:View編譯原理

來源:互聯網
上載者:User

通過.cshtml或者.vbhtml檔案定義的View能夠被執行,必須先被編譯成存在於某個程式集的類型,ASP.NET MVC採用動態編譯的方式對View檔案實施編譯。當我們在對ASP.NET MVC進行部署的時候,需要對.cshtml或者.vbhtml檔案進行打包。針對某個View的第一次訪問會觸發針對它的編譯,一個View對應著一個類型。我們可以對.cshtml或者.vbhtml進行修改,View檔案修改後的第一次訪問將會導致View的再一次編譯。和ASP.NET 傳統的編譯方式一樣,針對View的編譯預設是基於目錄的,也就是說同一個目錄下的多個View檔案被編譯到同一個程式集中。

為了讓讀者對ASP.NET MVC對View檔案的編譯機制具有一個深刻的認識,我們通過一個簡單的執行個體來確定View檔案最終都被編譯成什麼類型,所在的程式集又是哪一個。我們在一個ASP.NET MVC應用中為HtmlHelper定義了如下一個擴充方法ListViewAssemblies,該方法用於擷取當前被載入的包含View類型的程式集(程式集名稱以“App_Web_”為首碼)。

   1: public static class HtmlHelperExtensions
2: {
3: public static MvcHtmlString ListViewAssemblies(this HtmlHelper helper)
4: {
5: TagBuilder ul = new TagBuilder("ul");
6: foreach(var assembly in AppDomain.CurrentDomain.GetAssemblies().Where(a=>a.FullName.StartsWith("App_Web_")))
7: {
8: TagBuilder li = new TagBuilder("li");
9: li.InnerHtml = assembly.FullName;
10: ul.InnerHtml+= li.ToString();
11: }
12: return new MvcHtmlString(ul.ToString());
13: }
14: }

然後我們定義了如下兩個Controller類型(FooController和BarController),它們之中各自訂了兩個Action方法Action1和Action2。

   1: public class FooController : Controller
2: {
3: public ActionResult Action1()
4: {
5: return View();
6: }
7: public ActionResult Action2()
8: {
9: return View();
10: }
11: }
12: 
13: public class BarController : Controller
14: {
15: public ActionResult Action1()
16: {
17: return View();
18: }
19: public ActionResult Action2()
20: {
21: return View();
22: }
23: }

接下來我們為定義在FooController和BarController的四個Action建立對應的View(對應檔案路為:“~/Views/Foo/Action1.cshtml”、“~/Views/Foo/Action2.cshtml”、“~/Views/Bar/Action1.cshtml”和“~/Views/Bar/Action2.cshtml”)。它們具有如下相同的定義,我們在View中顯示自身的類型和當前載入的基於View的程式集。

   1: <div>當前View類型:@this.GetType().AssemblyQualifiedName</div>
2: <div>當前載入的View程式集:</div>
3: @Html.ListViewAssemblies()

現在運行我們的程式並在瀏覽器中通過輸入相應的地址“依次”(“Foo/Action1”、“Foo/Action2”、“Bar/Action1”和“Bar/Action2”)訪問定義在FooController和BarController的四個Action,四次訪問得到的輸出結果下圖所示。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.