Difference Between ViewData, ViewBag and TempData in MVC

ViewData is used to pass data from controller to view.
It is derived from ViewDataDictionary class.
It is available for the current request only.
Requires typecasting for complex data type and checks for null values to avoid error.
If redirection occurs, then its value becomes null.

In this example, a string value is set in the ViewData object in Controller and it is then displayed in View.
Controller
public class FirstController : Controller
{
    public ActionResult Index()
    {
        ViewData["Message"] = "Hello MVC!";
        return View();
    }
}

View
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @ViewData["Message"]
    </div>
</body>
</html>

--------------------------------------

ViewBag is also used to pass data from the controller to the respective view.
ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
It is also available for the current request only.
If redirection occurs, then its value becomes null.
Doesn’t require typecasting for complex data type.

In this example, a string value is set in the ViewBag object in Controller and it is then displayed in View.
Controller
public class FirstController : Controller
{
    public ActionResult Index()
    {
        ViewBag.Message = "Hello MVC!";
        return View();
    }
}

View
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @ViewBag.Message
    </div>
</body>
</html>

--------------------------------------

TempData is derived from TempDataDictionary class.
TempData is used to pass data from the current request to the next request.
It keeps the information for the time of an HTTP Request. This means only from one page to another. It helps to maintain the data when we move from one controller to another controller or from one action to another action.
It requires typecasting for complex data type and checks for null values to avoid error. Generally, it is used to store only one time messages like the error messages and validation messages.

In this example, a string value is set in the TempData object in Controller and it is redirected to another Controller and finally it is displayed in View.
First Controller
public class FirstController : Controller
{
    public ActionResult Index()
    {
        TempData["Message"] = "Hello MVC!";
        return new RedirectResult(@"~\Second\");
    }
}

Second Controller
public class SecondController : Controller
{
    public ActionResult Index()
    {
        return View();
    }
}

View of Second Controller
<html>
<head>
    <meta name="viewport" content="width=device-width"/>
    <title>Index</title>
</head>
<body>
    <div>
        @TempData["Message"];
    </div>
</body>
</html>