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

ASP.NET MVC 框架(三):ViewData 傳遞方式全解析——從 ViewDataDictionary 到強型別 ViewModel

     編輯:關於ASP.NET

系列第三篇,深入探討 Controller 向 View 傳遞資料的三種主要方式:ViewDataDictionary、ViewData.Model (強型別)、TempData,並說明各自適用場景與最佳實踐。

前情提要:MVC 核心分工

  • Controller:處理請求、執行商業邏輯、準備資料。
  • View:純粹呈現邏輯,從 Controller 取得資料產生 HTML。
  • ViewData:Controller 與 View 之間的資料傳遞容器。

Controller-View 交互圖

簡單產品列表場景

產品列表頁面

方式一:ViewDataDictionary (弱型別字典)

public ActionResult Index()
{
    var products = _repo.GetAll();
    ViewData["Products"] = products; // key-value 存放
    ViewData["PageTitle"] = "產品目錄";
    return View();
}

View 中取用:

<h1><%= ViewData["PageTitle"] %></h1>
<% foreach (var p in (IEnumerable<Product>)ViewData["Products"]) { %>
    <div><%= p.Name %> - <%= p.Price.ToString("C") %></div>
<% } %>

缺點:需型別轉換、無 IntelliSense、拼字錯誤執行時才發現。

方式二:強型別 ViewData.Model (推薦)

public ActionResult Index()
{
    var products = _repo.GetAll();
    return View(products); // 直接傳遞模型,隱含存入 ViewData.Model
}

View 頁面宣告模型型別:

<%@ Page Inherits="System.Web.Mvc.ViewPage<IEnumerable<Product>>" %>
<h1>產品目錄</h1>
<% foreach (var p in Model) { %> <!-- 直接使用 Model,IntelliSense 完整支援 --%>
    <div><%= p.Name %> - <%= p.Price.ToString("C") %></div>
<% } %>

優點:編譯時期型別檢查、完整 IntelliSense、重構安全、程式碼可讀性高。

方式三:ViewModel 模式 (複雜頁面最佳實踐)

當 View 需要多個不相關資料集 (如:產品列表 + 分類導航 + 使用者資訊 + 廣告),建立專用 ViewModel:

public class ProductListViewModel
{
    public IEnumerable<Product> Products { get; set; }
    public IEnumerable<Category> Categories { get; set; }
    public UserProfile CurrentUser { get; set; }
    public Advertisement BannerAd { get; set; }
}

public ActionResult Index()
{
    var vm = new ProductListViewModel
    {
        Products = _repo.GetAll(),
        Categories = _repo.GetCategories(),
        CurrentUser = GetCurrentUser(),
        BannerAd = _adRepo.GetRandomBanner()
    };
    return View(vm);
}

View 繼承 `<%@ Page Inherits=\"ViewPage\" %>`,單一模型承載所有所需資料。

TempData:跨請求暫存資料

  • 儲存於 Session,讀取後自動刪除 (或標記 Keep)。
  • 適用場景:PRG 模式下跨 Redirect 傳遞成功訊息、驗證錯誤。
[HttpPost]
public ActionResult Create(Product product)
{
    if (ModelState.IsValid)
    {
        _repo.Add(product);
        TempData["SuccessMessage"] = "產品已新增";
        return RedirectToAction("Index");
    }
    return View(product);
}

// Index View
<% if (TempData["SuccessMessage"] != null) { %>
    <div class="alert-success"><%= TempData["SuccessMessage"] %></div>
<% } %>

總結比較

最佳實踐建議

  1. 預設使用 強型別 View(Model)。
  2. 頁面資料來源超過 1-2 個 → 建立 ViewModel。
  3. 跨 Redirect 需傳遞提示訊息 → TempData。
  4. 避免在 View 中進行型別轉換或商業邏輯判斷。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
方式型別安全IntelliSense適用場景生命週期
ViewData[key]否無簡單單一資料、動態屬性單一請求
View(Model)是完整單一主要資料集單一請求
ViewModel是完整複雜頁面、多資料來源單一請求
TempData[key]否無跨 Redirect 傳遞暫時資訊下一請求 (讀取即刪)