HTML Helper 是 MVC 中產生 HTML 標籤的核心工具,輕量級且無 ViewState 負擔,掌握其用法能大幅提升開發效率與程式碼可維護性。
HTML Helper 類似傳統 ASP.NET Web Forms 的伺服器控制項,但更輕量:
MVC 內建涵蓋常用 HTML 元素:
ActionLink、RouteLinkTextBox、Password、TextArea、CheckBox、RadioButton、DropDownList、ListBox、HiddenBeginForm、EndFormValidationSummary、ValidationMessage、ValidationMessageFor最常用的導航 Helper,產生指向控制器 Action 的錨點標籤:
@Html.ActionLink("連結文字", "Action名稱")
@Html.ActionLink("連結文字", "Action名稱", "Controller名稱")
@Html.ActionLink("關於我們", "About")
// 輸出: <a href="/Home/About">關於我們</a>
| 參數 | 說明 |
|---|---|
| linkText | 連結顯示文字 |
| actionName | 目標 Action 名稱 |
| routeValues | 傳遞給 Action 的路由參數(匿名物件) |
| controllerName | 目標 Controller 名稱 |
| htmlAttributes | 額外 HTML 屬性(class、id、style 等) |
| protocol | 指定協定(http/https) |
| hostname | 指定主機名稱 |
| fragment | 錨點片段(#section) |
// Razor C#
@Html.ActionLink("編輯記錄", "Edit", new { id = 3 })
// 輸出: <a href="/Home/Edit/3">編輯記錄</a>
// Razor VB
@Html.ActionLink("編輯記錄", "Edit", New With {.id = 3})
完整的註冊表單展示:
<%= Html.ValidationSummary("建立失敗,請修正錯誤後重試。") %>
<% using (Html.BeginForm()) { %>
<p>
<label for="FirstName">名字:</label>
<%= Html.TextBox("FirstName") %>
<%= Html.ValidationMessage("FirstName", "*") %>
</p>
<p>
<label for="LastName">姓氏:</label>
<%= Html.TextBox("LastName") %>
<%= Html.ValidationMessage("LastName", "*") %>
</p>
<p>
<label for="Password">密碼:</label>
<%= Html.Password("Password") %>
<%= Html.ValidationMessage("Password", "*") %>
</p>
<p>
<label for="ConfirmPassword">確認密碼:</label>
<%= Html.Password("ConfirmPassword") %>
<%= Html.ValidationMessage("ConfirmPassword", "*") %>
</p>
<p>
<label for="Profile">個人簡介:</label>
<%= Html.TextArea("Profile", new { cols = 60, rows = 10 }) %>
</p>
<p>
<%= Html.CheckBox("ReceiveNewsletter") %>
<label for="ReceiveNewsletter" style="display:inline">訂閱電子報?</label>
</p>
<p><input type="submit" value="註冊" /></p>
<% } %>
TextBoxFor、EditorFor 等搭配模型綁定,享受編譯期檢查與重構支援ValidationMessageFor 顯示模型驗證錯誤| Helper 方法 | 用途 | 輸出標籤 |
|---|---|---|
| ActionLink | 動作連結 | <a> |
| BeginForm/EndForm | 表單標籤 | <form> |
| TextBox/TextBoxFor | 文字輸入框 | <input type="text"> |
| Password/PasswordFor | 密碼輸入框 | <input type="password"> |
| TextArea/TextAreaFor | 多行文字區域 | <textarea> |
| CheckBox/CheckBoxFor | 核取方塊 | <input type="checkbox"> |
| RadioButton/RadioButtonFor | 選項按鈕 | <input type="radio"> |
| DropDownList/DropDownListFor | 下拉選單 | <select> |
| ListBox/ListBoxFor | 清單方塊 | <select multiple> |
| Hidden/HiddenFor | 隱藏欄位 | <input type="hidden"> |
| ValidationSummary | 彙總驗證錯誤 | <div class="validation-summary-errors"> |
| ValidationMessage/For | 單一欄位驗證訊息 | <span class="field-validation-error"> |