Passing Data Using ViewData in .NET Core – Beginner Guide
👋 Introduction
If you are new to MVC, this topic is super important.
Today, we will talk about Passing Data Using ViewData in .net core in a very simple way.
At first, this concept may feel confusing, but don’t worry.
Because once it clicks, your confidence will jump 🚀.
So relax, read slowly, and enjoy learning like a friend is guiding you.
📚 What you are going to learn in this lesson
By the end of this lesson, you will clearly understand how ViewData works.
✔️ What ViewData is and why it exists
✔️ How data moves from Controller to View
✔️ When ViewData is a good choice
✔️ A real-life style example you can relate to
🌍 Real-world idea (before code)
Think about a notice board in a school.
The teacher writes a message.
Students come and read it.
Here,
- Teacher = Controller
- Notice board = ViewData
- Students = View
Simple, right? 😊
🧠 Passing Data Using ViewData in .net core – Core Idea
In MVC, the controller prepares data.
Then the view shows that data.
However, the controller cannot directly talk to the view.
So ViewData acts as a middle messenger.
ViewData stores data in key–value format.
Later, the view reads it using the same key.
💻 Simple Code Example (Step by Step)
Controller Code
public IActionResult Index()
{
ViewData["Message"] = "Welcome to ASP.NET Core!";
return View();
}
View Code (Index.cshtml)
<h2>@ViewData["Message"]</h2>
✅ Output
Welcome to ASP.NET Core!
🧾 Explanation
- First, the controller stores text in ViewData.
- The key name is
"Message". - Then the view reads that value.
- Finally, the text appears on the screen.
Easy and clean 👍
💡 One More Easy Example
Controller Code
ViewData["Today"] = DateTime.Now.ToShortDateString();
View Code (Index.cshtml)
<p>Today is: @ViewData["Today"]</p>
✅ Output
Today is: 07-06-2025
🧾 Explanation
Here, ViewData helps show small information quickly. So it is perfect for messages, titles, and dates.
🧑🔧 Real-Life Scenario (Why It Matters)
Imagine your app crashes.
You fix the issue.
Now you want to show a message like “Issue resolved successfully”.
Instead of creating a full model, you use ViewData.
Because the message is small and temporary.
That’s why Passing Data Using ViewData in .net core saves time and effort.
It keeps things simple when the data is simple.
⚠️ When NOT to Use ViewData
ViewData is helpful, but not perfect.
❌ Not type-safe
❌ Not good for large data
❌ Keys must match exactly
So use it wisely.
Later, you’ll learn better options for complex data.
👉 Next what?
Great job reaching here ✨
You’ve taken an important step today.
In the next chapter you will learn Passing Data Using ViewData in .net core, but in comparison with another cleaner option.
So stay curious and keep going 🚀
