`
<configuration>
<system.web>
<pages>
<tagMapping>
<!-- 將所有 asp:Label 對應至自訂 EnhancedLabel -->
<add tagType="System.Web.UI.WebControls.Label"
mappedTagType="MyProject.Controls.EnhancedLabel, MyProject" />
<!-- 將 GridView 對應至自訂 GridViewEx (支援匯出、固定表頭) -->
<add tagType="System.Web.UI.WebControls.GridView"
mappedTagType="MyProject.Controls.GridViewEx, MyProject" />
<!-- WebPartManager 對應 SharePoint 相容實作 -->
<add tagType="System.Web.UI.WebControls.WebParts.WebPartManager"
mappedTagType="Microsoft.SharePoint.WebPartPages.SPWebPartManager, Microsoft.SharePoint, Version=15.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
</tagMapping>
</pages>
</system.web>
</configuration>
namespace MyProject.Controls
{
public class EnhancedLabel : System.Web.UI.WebControls.Label
{
protected override void OnPreRender(EventArgs e)
{
// 1. 確保 CssClass 包含基礎樣式
if (!CssClass.Contains("form-label")) CssClass += " form-label";
// 2. 自動 HTML 編碼 Text (防 XSS),除非明確設定 Encode="false"
// 需自行擴充 Encode 屬性 (略)
base.OnPreRender(e);
}
protected override void RenderContents(HtmlTextWriter writer)
{
// 範例:在文字前加前綴
writer.Write("【標籤】");
base.RenderContents(writer);
}
}
}
public class GridViewEx : GridView
{
public override void VerifyRenderingInServerForm(Control control) { } // 允許 RenderControl 匯出
public void ExportToExcel(string fileName)
{
Response.Clear();
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("Content-Disposition", $"attachment;filename={fileName}.xlsx");
// 使用 EPPlus/NPOI 產生真正 .xlsx (略)
Response.End();
}
}
<asp:Label ID="lblTitle" runat="server" Text="標題" CssClass="title" />
<asp:GridView ID="gvData" runat="server" AutoGenerateColumns="True" />
<span id="lblTitle" class="title form-label">【標籤】標題</span>
<div class="gridviewex">...</div>
| 條件 | 說明 |
|---|---|
| 目標類別需為 public 且可實例化 | 不可為 abstract / internal |
| 需繼承原控制項類別 | `mappedTagType` 必須繼承 `tagType` |
| 僅影響伺服器端控制項 | 純 HTML 標籤 (` |
| 需重新編譯網站 | 修改 web.config 後需 Rebuild / IIS 重啟 |
| 不支援泛型控制項 | 如 `GridView |