Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

วิธีใช้ ViewBag ใน ASP.NET MVC C#

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 ใน ASP.NET MVC C#

ViewBag vs ViewData vs TempData vs ViewModel

FeatureViewBagViewDataTempDataViewModel
TypeDynamicDictionaryDictionaryStrongly Typed Class
SyntaxViewBag.PropertyViewData["Key"]TempData["Key"]@model Type
IntelliSenseไม่มีไม่มีไม่มีมีเต็มรูปแบบ
Compile Checkไม่มีไม่มีไม่มีมี
Refactoring Safeไม่ไม่ไม่ใช่
LifetimeCurrent RequestCurrent RequestNext RequestCurrent Request
Redirect Survivalไม่ (Null)ไม่ (Null)ใช่ไม่ (ต้องส่งใหม่)

ข้อควรระวัง

  • Typos ไม่ถูกจับตอน Compile: ViewBag.Countrys vs ViewBag.Countries - Runtime Error เท่านั้น
  • Null Reference: Access Property ที่ไม่ได้ Set จะได้ Null → Exception ตอน Runtime
  • Performance: Dynamic Dispatch ช้ากว่า Strongly Typed เล็กน้อย
  • ไม่เหมาะสำหรับข้อมูลสำคัญ/ซับซ้อน - ควรใช้ ViewModel

Best Practices

  1. ใช้ ViewModel สำหรับข้อมูลหลักของ View (Strongly Typed)
  2. ใช้ ViewBag/ViewData สำหรับ Metadata เล็กๆ: Title, Breadcrumbs, Flags, Messages
  3. ใช้ TempData สำหรับข้อมูลข้าม Redirect (PRG Pattern)
  4. ใช้ 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