ViewData là dictionary của objects được lưu và truy xuất dùng strings làm keys. Nó dùng để transfer data từ Controller sang View. Vì ViewData là dictionary, nó chứa key-value pairs nơi mỗi key phải là string. ViewData chỉ transfer data từ controller đến view, không ngược lại. Nó chỉ valid trong current request.
Lưu data vào ViewData
ViewData["countries"] = countriesList;
Lấy data từ ViewData
string country = ViewData["MyCountry"].ToString();
ViewData không cung cấp compile-time error checking. Ví dụ, nếu gõ sai key names, không có compile-time error. Chỉ biết lỗi tại runtime.
Controller
Ví dụ
using System.Collections.Generic;
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers {
public class HomeController : Controller {
public ViewResult Index() {
ViewData["Countries"] = new List<string> {
"India", "Malaysia", "Dubai", "USA", "UK"
};
return View();
}
}
}
View
@{
ViewBag.Title = "Countries List";
}
<h2>Countries List</h2>
<ul>
@foreach(string country in (List<string>)ViewData["Countries"]) {
<li>@country</li>
}
</ul>
Output
Hiển thị danh sách các quốc gia.
ViewData vs ViewBag vs TempData vs Model
| Đặc điểm | ViewData | ViewBag | TempData | Model (ViewModel) |
|---|---|---|---|---|
| Kiểu | Dictionary<string, object> | Dynamic wrapper ViewData | Dictionary (session-backed) | Strongly typed class |
| Syntax | ViewData["Key"] | ViewBag.Key | TempData["Key"] | @model Type |
| Type safety | Không (cast tại runtime) | Không (dynamic) | Không | ✅ Có (compile-time) |
| IntelliSense | Không | Có (dynamic) | Không | ✅ Có |
| Lifetime | Current request | Current request | Next request (survive redirect) | Current request |
| Performance | Nhanh | Chậm hơn (DLR) | Chậm (session) | Nhanh |
| Best Practice | Tránh dùng | Tránh dùng | Chỉ cho redirect (PRG pattern) | ✅ Khuyến nghị |
Ví dụ ViewData phức tạp
public ActionResult Dashboard() {
ViewData["Title"] = "Dashboard";
ViewData["UserCount"] = 1250;
ViewData["IsAdmin"] = User.IsInRole("Admin");
ViewData["LastLogin"] = DateTime.Now.AddDays(-2);
ViewData["Notifications"] = new List { "Msg 1", "Msg 2" };
// Complex object - cần cast
ViewData["Report"] = new SalesReport { Total = 10000, Currency = "USD" };
return View();
}
// View
@{
var report = (SalesReport)ViewData["Report"]; // Cast bắt buộc
bool isAdmin = (bool)ViewData["IsAdmin"];
}
<h1>@ViewData["Title"]</h1>
<p>Users: @ViewData["UserCount"]</p>
Lưu ý quan trọng
- Luôn cast khi lấy object phức tạp:
(List<string>)ViewData["Key"] - Kiểm tra null trước khi dùng:
ViewData["Key"]?.ToString() - Không dùng cho dữ liệu quan trọng - ưu tiên Strongly Typed ViewModel
- Key là case-insensitive:
ViewData["key"] == ViewData["KEY"]