ASP.NET 將 Web 頁面視為伺服器端表單,引入事件驅動模型,讓 WinForms 開發者能快速上手。本文涵蓋首支程式、頁面指令、HTML 控件對應表與基本運作原理。
<%@ Page Language="VB" %>
<% Response.Write("Hello World") %>
.aspx,IIS 預設文件包含 Default.aspxResponse.Write 需用括號 ("..."),VB.NET 可省略位於 System.Web.UI.HtmlControls 命名空間,繼承自 HtmlControl。任何標籤加上 runat="server" 即成為伺服器控件。
| 控件類別 | 對應 HTML 標籤 |
|---|---|
| HtmlAnchor | <a> |
| HtmlButton | <button> |
| HtmlSelect | <select> |
| HtmlTextArea | <textarea> |
| HtmlInputText | <input type="text">、<input type="password"> |
| HtmlInputButton | <input type="button"> |
| HtmlInputCheckBox | <input type="checkbox"> |
| HtmlInputRadioButton | <input type="radio"> |
| HtmlInputHidden | <input type="hidden"> |
| HtmlInputFile | <input type="file"> |
| HtmlForm | <form> |
| HtmlImage | <img> |
| HtmlTable / HtmlTableRow / HtmlTableCell | <table> / <tr> / <td> |
| HtmlGenericControl | <span>、<div> 等無專屬控件的標籤 |
HTML 控件最大價值在於將傳統 ASP 頁面最小成本遷移至 ASP.NET:只需在現有標籤加入 runat="server" 與 id,即可在後端程式碼存取屬性、綁定事件,無需重寫 UI 結構。
<input type="text" runat="server" id="txtName" value="預設值" />
<script runat="server">
void Page_Load()
{
txtName.Value = "從後端設定"; // HtmlInputText 使用 Value 屬性
}
</script>