標準 HTML 標籤(如 <input>、<select>、<table>)預設在 ASP.NET 中視為純文字。加上 runat="server" 屬性後,即轉為伺服器端可程式化控制項,擁有 ID、事件、ViewState 等能力,且輸出 HTML 保持原生標籤,輕量高效。
<form runat="server"> 內。<input />、<option>...</option>。System.Web.UI.HtmlControls 命名空間。| 控制項類別 | 對應 HTML 標籤 | 常用屬性/事件 |
|---|---|---|
| HtmlAnchor | <a> | HRef, Target, ServerClick |
| HtmlButton | <button> | InnerHtml, ServerClick |
| HtmlForm | <form> | Action, Method, Enctype |
| HtmlGenericControl | <div>, <span>, <body>, <p> 等無專屬類別標籤 | TagName, InnerHtml, InnerText |
| HtmlImage | <img> | Src, Alt, Align, Border |
| HtmlInputButton | <input type="button|submit|reset"> | Value, ServerClick |
| HtmlInputCheckBox | <input type="checkbox"> | Checked, Value, ServerChange |
| HtmlInputFile | <input type="file"> | PostedFile, Accept |
| HtmlInputHidden | <input type="hidden"> | Value |
| HtmlInputImage | <input type="image"> | Src, Alt, ServerClick |
| HtmlInputRadioButton | <input type="radio"> | Checked, Value, GroupName, ServerChange |
| HtmlInputText | <input type="text|password"> | Value, MaxLength, Size, ServerChange |
| HtmlSelect | <select> | Items, SelectedIndex, Multiple, Size, ServerChange |
| HtmlTable | <table> | Rows, Border, CellPadding, CellSpacing |
| HtmlTableCell | <td>, <th> | InnerHtml, Align, VAlign, ColSpan, RowSpan |
| HtmlTableRow | <tr> | Cells, BgColor, Align |
| HtmlTextArea | <textarea> | Value, Rows, Cols, ServerChange |
<table id="tblData" runat="server" border="1" cellpadding="3" cellspacing="0"></table>
// Code-behind
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
var dt = GetData(); // DataTable
foreach (DataRow row in dt.Rows)
{
var tr = new HtmlTableRow();
foreach (DataColumn col in dt.Columns)
{
var td = new HtmlTableCell { InnerText = row[col].ToString() };
tr.Cells.Add(td);
}
tblData.Rows.Add(tr);
}
}
}
| 特性 | HTML 伺服器控制項 | Web 伺服器控制項 (asp:) |
|---|---|---|
| HTML 輸出 | 保持原生標籤 | 可能轉譯為複雜結構 (Table、Span 等) |
| 事件模型 | ServerClick/ServerChange | 豐富命令事件 |
| ViewState | 手動管理 | 自動管理 |
| 適用場景 | 靜態版面、整合前端框架、效能敏感 | 資料繫結、驗證、複雜互動 |