三種包含檔案方法
| 語法 | 執行時機 | 變數共享 | 適用場景 |
<% Response.WriteFile("path") %> | Render 階段直接輸出檔案內容 | **不共享** 變數/控制項 | 靜態 HTML 片段、頁尾版權、通用 Script |
<% Server.Execute("path") %> | 建立子請求執行目標頁面,**返回**繼續 | **不共享** 頁面層級變數 (各自獨立 Page 實例) | 動態元件化區塊、需獨立生命週期的子頁面 |
<!-- #include file="path" --> | **編譯前** 將檔案內容原文合併 | **完全共享** 變數、函數、控制項 | 傳統 ASP 相容、共用變數/函數庫 (不推薦新專案) |
程式碼範例
Response.WriteFile (靜態內容)
<!-- 頁尾版權 -->
<% Response.WriteFile("~/Includes/Footer.html") %>
Server.Execute (動態子頁面)
<%
// Parent.aspx
Server.Execute("ChildWidget.aspx?param=123");
%>
<!-- ChildWidget.aspx -->
<%@ Page Language="C#" %>
<script runat="server">
protected void Page_Load() { Label1.Text = Request["param"]; }
</script>
<asp:Label ID="Label1" runat="server" />
舊式 #include (不建議)
<!-- #include file="../Common/Utils.asp" --> <%-- VBScript 檔案 -->
<!-- #include file="Config.cs" --> <%-- C# 程式碼片段 -->
關鍵差異:Include vs Server.Execute
' Include.inc
Dim sharedVar = "Hello"
' Page1.asp
<!-- #include file="Include.inc" -->
Response.Write sharedVar ' 輸出 "Hello",變數可見
' Page2.asp (Server.Execute)
Server.Execute("Include.inc") ' 編譯錯誤:.inc 非合法 ASPX
' 正確用法需 .aspx
Server.Execute("SharedVars.aspx") ' 子頁面有自己的 sharedVar,父頁面不可見
現代最佳實務 (ASP.NET MVC / WebForms 4.5+)
- Partial View / UserControl:`@Html.Partial("_NavBar")` 或 ``,強型別、支援模型綁定。
- Layout/Master Page:全站版面統一管理。
- ViewComponent / Razor Components:獨立邏輯與渲染的可復用元件。
新專請忘記 `#include`,善用 Partial View、UserControl、ViewComponent 實現真正的元件化復用。