首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> ASP.NET 基礎 >> 關於ASP.NET

ASP.NET MVC 框架(四):表單編輯與提交場景完整實作——產品 CRUD 範例

     編輯:關於ASP.NET

系列第四篇,示範 MVC 處理表單輸入/提交的核心模式:產品列表、新增、編輯三大體驗,涵蓋 HTML Helper 表單生成、模型繫結、驗證、PRG 模式與安全性防範 (AntiForgeryToken)。

三大核心使用者體驗

  1. 分類產品列表:/Products/Category/{id}
  2. 新增產品:/Products/New (GET 顯示表單 / POST 處理提交)
  3. 編輯產品:/Products/Edit/{id}

Controller 實作

public class ProductsController : Controller
{
    private readonly IProductRepository _repo = new ProductRepository();

    // 列表
    public ActionResult Category(int id)
    {
        var products = _repo.GetByCategory(id);
        return View(products);
    }

    // 新增 - GET
    public ActionResult New()
    {
        ViewData["Categories"] = new SelectList(_repo.GetCategories(), "ID", "Name");
        return View(new Product()); // 空模型
    }

    // 新增 - POST
    [HttpPost]
    [ValidateAntiForgeryToken] // 防 CSRF
    public ActionResult New(Product product)
    {
        if (ModelState.IsValid)
        {
            _repo.Add(product);
            return RedirectToAction("Category", new { id = product.CategoryID }); // PRG 模式
        }
        ViewData["Categories"] = new SelectList(_repo.GetCategories(), "ID", "Name");
        return View(product); // 回傳含驗證錯誤的模型
    }

    // 編輯 - GET
    public ActionResult Edit(int id)
    {
        var product = _repo.GetById(id);
        if (product == null) return HttpNotFound();
        ViewData["Categories"] = new SelectList(_repo.GetCategories(), "ID", "Name", product.CategoryID);
        return View(product);
    }

    // 編輯 - POST
    [HttpPost]
    [ValidateAntiForgeryToken]
    public ActionResult Edit(Product product)
    {
        if (ModelState.IsValid)
        {
            _repo.Update(product);
            return RedirectToAction("Category", new { id = product.CategoryID });
        }
        ViewData["Categories"] = new SelectList(_repo.GetCategories(), "ID", "Name", product.CategoryID);
        return View(product);
    }
}

View 表單範例 (New.aspx / Edit.aspx 共用)

<%@ Page Inherits="System.Web.Mvc.ViewPage<Product>" %>
<% using (Html.BeginForm()) { %>
    <%= Html.AntiForgeryToken() %> <!-- CSRF 保護 --%>
    <fieldset>
        <legend>產品資訊</legend>

        <div class="editor-label"><%= Html.LabelFor(m => m.Name) %></div>
        <div class="editor-field">
            <%= Html.TextBoxFor(m => m.Name) %>
            <%= Html.ValidationMessageFor(m => m.Name) %>
        </div>

        <div class="editor-label"><%= Html.LabelFor(m => m.Price) %></div>
        <div class="editor-field">
            <%= Html.TextBoxFor(m => m.Price) %>
            <%= Html.ValidationMessageFor(m => m.Price) %>
        </div>

        <div class="editor-label"><%= Html.LabelFor(m => m.CategoryID) %></div>
        <div class="editor-field">
            <%= Html.DropDownListFor(m => m.CategoryID, (SelectList)ViewData["Categories"], "-- 選擇分類 --") %>
        </div>

        <input type="submit" value="儲存" />
    </fieldset>
<% } %>

關鍵模式總結

安全性補充

  • 大量指派攻擊:使用 Bind 屬性白名單 (`[Bind(Include=\"Name,Price,CategoryID\")]`) 或 ViewModel 限制可繫結屬性。
  • XSS 防護:Razor 預設編碼輸出,舊版 WebForms View Engine 需手動 `<%: %>`。

完整原始碼下載連結文末提供,建議下載實際執行體驗。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
模式說明程式碼體現
PRG (Post-Redirect-Get)POST 成功後 Redirect,防止重新整理重複提交return RedirectToAction(...)
模型繫結表單欄位自動映射到 Action 參數屬性public ActionResult New(Product product)
DataAnnotations 驗證模型屬性標註驗證規則,ModelState 自動檢查[Required], [Range] 等
HTML Helpers強型別產生表單元素,支援驗證訊息顯示Html.TextBoxFor, Html.ValidationMessageFor
AntiForgeryToken防止跨站請求偽造[ValidateAntiForgeryToken] + Html.AntiForgeryToken()