Quantcast
Viewing all articles
Browse latest Browse all 2367

CSHTML Layout Page、Partial View 執行順序實驗

維護 ASP.NET MVC 專案遇上巢狀 Layout 引用 Partial View 的情境,無法斷定執行先後順序,想必是自己觀念不清,做了以下實驗驗證,順手分享之。

假設有 ASP.NET MVC 巢狀 Layout 並混用 Partial View 結構如下:

Image may be NSFW.
Clik here to view.

_Layout.cshtml

@{
    System.Diagnostics.Debug.WriteLine("_Layout.cshtml");
}<!DOCTYPE html><html><head><meta charset="utf-8" /><meta name="viewport" content="width=device-width, initial-scale=1.0"><title>@ViewBag.Title</title></head><body>

@Html.Partial("_PartView1")

@RenderBody()

</body></html>

_PartView1.cshtml (_PartView2.cshtml 及 _PartView3.cshtml 做法相同,只有數字不同)

@{
    System.Diagnostics.Debug.WriteLine("PartialView1");
}<div>Partial View 1</div>

_NestedLayout.cshtml

@{
    Layout = "~/Views/Shared/_Layout.cshtml";
    System.Diagnostics.Debug.WriteLine("_NestedLayout.cshtml");
}
@Html.Partial("_PartView2")
@RenderBody()

Index.cshtml

@{
    Layout = "~/Views/Shared/_NestedLayout.cshtml";
    System.Diagnostics.Debug.WriteLine("Index.cshtml");
}

@Html.Partial("_PartView3")<h2>Index</h2>

HomeController.cs

    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            System.Diagnostics.Debug.WriteLine("Index Action");
            return View();
        }
    }

執行結果不難預期:

Image may be NSFW.
Clik here to view.

問題來了,HomeController.cs、Index.cshtml、_PartView1.cshtml、_PartView2.cshtml、_PartView3.cshtml、_NestedLayout.cshtml、_Layout.cshtml 都埋了 System.Diagnostics.Debug.WriteLine(),將以什麼順序執行?

給大家 20 秒自我測驗。

答案揭曉:

Image may be NSFW.
Clik here to view.

HomeController Index Action –> Index.cshtml –> Partial View 3 –> _NestedLayout –> Partial View 2 -> _Layout –> Partial View 1

這順序不難理解,基本上就是從 HomeController.cs 開始,從 Index.cshtml、_NestedLayout.cshtml 到 _Layout.cshtml,由內而外的順序將 Razor View 轉為 HTML,生成 HTML 過程才載入 Partial View。

(原想找到官方文件證實,搜索未獲,十方大德如有知悉懇請不吝補充)

Image may be NSFW.
Clik here to view.

Viewing all articles
Browse latest Browse all 2367

Trending Articles