Tutorials ASP.NET Core MVC Mastery

ViewData vs ViewBag

On this page

Data Passing: ViewData, ViewBag, and the ViewModel Revolution

ViewData: The Fast Dictionary

ViewData is a dictionary of objects that is derived from the ViewDataDictionary class. It uses string keys to store data.


// In Controller
ViewData["Greeting"] = "Hello Specialist!";
// In View
<h1>@ViewData["Greeting"]</h1>
                        

ViewBag: The Dynamic Wrapper

ViewBag is a dynamic property that is essentially a wrapper around ViewData. It allows you to use property-like syntax.


// In Controller
ViewBag.Greeting = "Hello Architect!";
// In View
<h1>@ViewBag.Greeting</h1>
                        

The "Expert" Verdict: Stop Using Both!

If you have more than 3 years of experience, you should almost NEVER use ViewData or ViewBag. Why? Because they are **Weakly Typed**. You get zero IntelliSense and zero compile-time error checking. One typo in a string key like ViewData["Greetng"] and your site crashes in production.

The ViewModel Pattern (12-Year Standard)

Always create a dedicated class for your view. This ensures 100% type safety and makes your views extremely clean.


public class UserDashboardViewModel {
    public string UserName { get; set; }
    public List RecentOrders { get; set; }
}
                        

Senior Pro-Tip #99: TempData Persistence

Did you know that TempData data is deleted as soon as it is read? If you need it to persist for another redirect, you MUST call TempData.Keep(). This is a common bug in shopping cart checkout flows!

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

ASP.NET Core MVC Mastery
Course syllabus
1. Core Framework
MODULE 1: INTRODUCTION & ENVIRONMENT SETUP
2. View Engine
MODULE 2: .NET CORE FUNDAMENTALS
MODULE 3: ASP.NET CORE BASICS
MODULE 4: MVC FUNDAMENTALS
MODULE 5: DATA PASSING TECHNIQUES
MODULE 6: ROUTING
MODULE 7: VIEWS & UI
MODULE 8: ACTION RESULTS
MODULE 9: HTML HELPERS
MODULE 10: TAG HELPERS
MODULE 11: MODEL BINDING
MODULE 12: VALIDATION
MODULE 13: STATE MANAGEMENT
MODULE 14: FILTERS & SECURITY
MODULE 15: ENTITY FRAMEWORK CORE (DEEP DIVE)
MODULE 16: DESIGN PATTERNS
MODULE 17: FILE HANDLING
MODULE 18: ADVANCED ASP.NET CORE
MODULE 19: PERFORMANCE & BEST PRACTICES
MODULE 20: RAZOR PAGES (BONUS)
MODULE 21: REAL-WORLD PROJECTS (🔥 MUST DO)
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details