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

ASP.NET MVC 案例教程(四):表單資料傳遞與模型繫結實戰

     編輯:關於ASP.NET

系列第四篇,解決 MVC 核心問題:表單資料如何從瀏覽器傳遞到 Controller 處理。以「公告發布系統」為例,完整示範建立輸入頁面、下拉選單繫結、表單提交與模型繫結流程。

修正實體類別

補充 AnnounceInfo 缺少的 Category 屬性 (int),對應公告分類。

建立輸入頁面 Controller

public class AnnounceController : Controller
{
    public ActionResult Release()
    {
        // 取得所有分類,轉為 SelectList 供下拉選單繫結
        ICategoryService cServ = ServiceBuilder.BuildCategoryService();
        List<CategoryInfo> categories = cServ.GetAll();
        ViewData["Categories"] = new SelectList(categories, "ID", "Name");
        
        return View("Release");
    }
}

SelectList 三參數建構說明

new SelectList(items, dataValueField, dataTextField)
// items: IEnumerable 來源集合
// dataValueField: 對應 option value 的屬性名 (ID)
// dataTextField: 對應顯示文字的屬性名 (Name)

View 頁面 (Release.aspx) 表單範例

<% using (Html.BeginForm("Save", "Announce", FormMethod.Post)) { %>
    <fieldset>
        <legend>發布公告</legend>
        
        <div class="editor-label">
            <%= Html.LabelFor(m => m.Title) %>
        </div>
        <div class="editor-field">
            <%= Html.TextBoxFor(m => m.Title) %>
            <%= Html.ValidationMessageFor(m => m.Title) %>
        </div>

        <div class="editor-label">
            <%= Html.LabelFor(m => m.Content) %>
        </div>
        <div class="editor-field">
            <%= Html.TextAreaFor(m => m.Content) %>
        </div>

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

        <input type="submit" value="發布" />
    </fieldset>
<% } %>

表單提交處理 Action

[HttpPost]
public ActionResult Save(AnnounceInfo model)
{
    if (ModelState.IsValid)
    {
        IAnnounceService serv = ServiceBuilder.BuildAnnounceService();
        serv.Add(model);
        return RedirectToAction("Index");
    }
    // 驗證失敗:重新載入分類下拉選單並回傳 View
    ViewData["Categories"] = new SelectList(
        ServiceBuilder.BuildCategoryService().GetAll(), "ID", "Name");
    return View("Release", model);
}

核心機制總結

  1. GET Release:Controller 準備 ViewData (SelectList) → View 呈現表單。
  2. 使用者填寫提交:瀏覽器 POST 表單資料 (application/x-www-form-urlencoded)。
  3. 模型繫結器:自動將表單欄位對應到 AnnounceInfo 屬性 (Name/ID 比對)。
  4. Action 參數接收模型:Save(AnnounceInfo model) 直接獲得繫結後物件。
  5. 驗證與處理:ModelState.IsValid 檢查 → 成功存庫導向、失敗回傳 View 保留輸入值。

關鍵差異:MVC vs WebForms

特性WebForms (Model 1)MVC (Model 2)
表單提交目標同名 .aspx.cs 後置程式碼Controller Action (路由決定)
資料繫結手動 FindControl 取值自動模型繫結器
驗證Validator 控件DataAnnotations + ModelState
關注點分離UI 與邏輯混雜Controller/ Model/ View 明確分離

掌握表單傳遞與模型繫結,即掌握 MVC 互動核心。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved