ViewBag ใช้ Dynamic Feature ที่ Introduce ใน C# 4.0 อนุญาตให้ Object มี Properties เพิ่มได้แบบ Dynamic ภายในเป็น Dynamic Type Property ของคลาส ControllerBase ซึ่งเป็น Base Class ของ Controller Class
ViewBag ส่งข้อมูลจาก Controller ไป View เท่านั้น ไม่ใช่สองทาง ViewBag Values จะเป็น Null ถ้าเกิด Redirection ViewBag สามารถ Set และ Get Value แบบ Dynamic และเพิ่ม Fields เพิ่มเติมได้ไม่จำกัดโดยไม่ต้อง Convert เป็น Strongly Typed
การเก็บข้อมูลใน ViewBag
ViewBag.Counties = countriesList;
การดึงข้อมูลจาก ViewBag
string country = ViewBag.Countries;
Controller
using System.Collections.Generic;
using System.Web.Mvc;
namespace DemoMvcApplication.Controllers {
public class HomeController : Controller {
public ViewResult Index() {
ViewBag.Countries = new List {
"India", "Malaysia", "Dubai", "USA", "UK"
};
return View();
}
}
}
View
@{
ViewBag.Title = "Countries List";
}
Countries List
@foreach(string country in ViewBag.Countries) {
- @country
}
Output

ViewBag vs ViewData vs TempData vs ViewModel
| Feature | ViewBag | ViewData | TempData | ViewModel |
|---|---|---|---|---|
| Type | Dynamic | Dictionary | Dictionary | Strongly Typed Class |
| Syntax | ViewBag.Property | ViewData["Key"] | TempData["Key"] | @model Type |
| IntelliSense | ไม่มี | ไม่มี | ไม่มี | มีเต็มรูปแบบ |
| Compile Check | ไม่มี | ไม่มี | ไม่มี | มี |
| Refactoring Safe | ไม่ | ไม่ | ไม่ | ใช่ |
| Lifetime | Current Request | Current Request | Next Request | Current Request |
| Redirect Survival | ไม่ (Null) | ไม่ (Null) | ใช่ | ไม่ (ต้องส่งใหม่) |
ข้อควรระวัง
- Typos ไม่ถูกจับตอน Compile:
ViewBag.CountrysvsViewBag.Countries- Runtime Error เท่านั้น - Null Reference: Access Property ที่ไม่ได้ Set จะได้ Null → Exception ตอน Runtime
- Performance: Dynamic Dispatch ช้ากว่า Strongly Typed เล็กน้อย
- ไม่เหมาะสำหรับข้อมูลสำคัญ/ซับซ้อน - ควรใช้ ViewModel
Best Practices
- ใช้ ViewModel สำหรับข้อมูลหลักของ View (Strongly Typed)
- ใช้ ViewBag/ViewData สำหรับ Metadata เล็กๆ: Title, Breadcrumbs, Flags, Messages
- ใช้ TempData สำหรับข้อมูลข้าม Redirect (PRG Pattern)
- ใช้ Constants สำหรับ Key Names ป้องกัน Typo
// Good: ViewModel for main data
public class HomeViewModel {
public List Countries { get; set; }
public string PageTitle { get; set; }
public int TotalCount { get; set; }
}
// Controller
public ActionResult Index() {
var model = new HomeViewModel {
Countries = _service.GetCountries(),
PageTitle = "Countries List",
TotalCount = 5
};
return View(model);
}
// View (Strongly Typed)
@model HomeViewModel
@Model.PageTitle
Total: @Model.TotalCount