image

Introduction

When working with ASP.NET MVC, we often need to pass data:

ASP.NET MVC provides three ways to pass data:

Many beginners get confused:

In this article, we will understand everything in very simple language with example and output.

Why Do We Need to Pass Data?

In MVC:

If the controller has some message or data, how will it send it to the view?

That is why we use:

ViewData

What is ViewData?

ViewData is a dictionary object used to pass data:

It works like a key-value pair.

Why Use ViewData?

We use ViewData when:

Example of ViewData

Controller

public ActionResult Index()
{
    ViewData["Message"] = "Hello from ViewData";
    return View();
}

View (Index.cshtml)

<h2>@ViewData["Message"]</h2>

Output

When you run:

https://localhost:xxxx/Home/Index

You will see:

Hello from ViewData

Important Note

If you refresh the page, data still works (same request).

But if you redirect to another action, ViewData will not work.

ViewBag

What is ViewBag?

ViewBag is a dynamic object used to pass data:

It is easier to use than ViewData.

Why Use ViewBag?

Example of ViewBag

Controller

public ActionResult Index()
{
    ViewBag.Message = "Hello from ViewBag";
    return View();
}

View

<h2>@ViewBag.Message</h2>

Output

Hello from ViewBag

ViewData vs ViewBag

Both work the same way.

Difference is:

Internally, ViewBag uses ViewData.

TempData

What is TempData?

TempData is used to pass data:

It stores data temporarily.

Why Use TempData?

We use TempData when:

Example of TempData

Controller

public ActionResult Index()
{
    TempData["Message"] = "Data saved successfully!";
    return RedirectToAction("About");
}

public ActionResult About()
{
    return View();
}

About View

<h2>@TempData["Message"]</h2>

Output

Data saved successfully!

Important

TempData works only once.

After reading it, data is removed automatically.

Comparison Table (Easy to Understand)

FeatureViewDataViewBagTempData
TypeDictionaryDynamicDictionary
ScopeCurrent requestCurrent requestNext request
Used ForController → ViewController → ViewRedirect
LifetimeUntil request endsUntil request endsUntil read

Real-Life Example (Very Easy)

Imagine a teacher giving homework.

When Should You Use What?

Use ViewData when:

Use ViewBag when:

Use TempData when:

Conclusion

In this article, we learned: