WebForms And MVC


  1. 說明
    1. LifeCycle
    2. Layout & View

根據 Rebuilding Web Forms Applications in MVC 課程心得,筆記 ASP.NET Web Forms 與 MVC 的殊異之處。

logo

說明

LifeCycle

ASP.NET Web Forms 以及 ASP.NET MVC 有著相同的基底平台也就是 ASP.NET,在 ASP.NET 的 Request 生命週期上,Web Forms 與 MVC 最直接的差別在於負責的 HTTP Handler 不同。在 ASP.NET MVC 中只有單一個 Handler,並且根據生命週期先前的路由判斷,由產生的 Controller 進行 Request 處理;而 Web Forms 每一支 .aspx 程式都是一個獨立的 Handler 用於處理 Request。

ASP.NET 的 Application Life Cycle

  • BeginRequest
  • AuthenticateRequest
  • AuthorizeRequest
  • ResolveRequestCache (URL Routing)
  • MapRequestHandler
  • AcquireRequestState
  • RequestHandlerExecute (MVC or Web Forms)
  • UpdateRequestCache
  • LogRequest
  • EndRequest

而在 RequestHandlerExecute 階段,Web Forms ViewState 以及 Validation 的機制發生於此,並且有自己的 Page Life Cycle

Inti
初始化控制項的程式碼
Load
處理控制項相關的邏輯與資料,包含 ViewState 以及表單資料等
Validate
進行頁面層級的檢查控制項
Control Events
處理 Event Handler 例如按鈕等
Render
渲染與生成 HTML

ASP.NET MVC 也有自己的 Request Life Cycle

Controller Initialization
根據先前在 Application Life Cycle ResolveRequestCache 階段所解析的路由資訊,決定 Controller
Action Method Execution
產生回應的資料與資料格式
Action Result Execution
將資料寫入 Response Stream
View Engine
對於 HTML 回應類型的資料,進行渲染

Layout & View

Web Forms 在處理頁面的渲染上,包含使用 Master Page 作為網頁的 Layout 檔,可以用於重複使用的 Scripts / Style 參考處理,而可重複使用的元件部分,則以副檔名 .ascx 抽出並使用。另外最重要的是 Web Forms 元件稱為控制項 (Controls),搭配 Web Forms 的 ViewState 機制進行資料的邏輯處理與呈現。

相同於 Web Forms,MVC 有對應的 Layout, View (.cshtml) 以及 PartialView (.cshtml),需要插入的內容可以在 Layout 中挖 Section 讓 View 去填補。

相對於 Web Forms 元件的控制項,MVC 使用原生的 HTML,搭配 Property 以及 CSS 進行網頁呈現與互動,並且提供豐富的 HTML Helper 協助產生 HTML。

而最重要的是 Razor 引擎讓頁面的渲染更為方便與直觀,不同於 Web Forms 使用的 Code-Behind 將頁面與程式碼分隔成 .aspx 以及 .aspx.cs