ViewBag, ViewData, And TempData In MVC

ViewBag, ViewData, And TempData In MVC
ViewBag, ViewData, And TempData In MVC

Introduction

In the previous article, you have learned about Code first approach and how to Connect your SQL database to MVC application using the Code First approach.

In this article, you will learn the basics and how to use ViewBag, ViewData, and TempData.

ViewBag, ViewData, and TempData all are objects in ASP.NET MVC and these are used to pass the data in various scenarios like the controller to view, or controller to view another controller.

This article will be helpful to beginners and students who are learning MVC. 

ViewBag

ViewBag is a dynamic object that is used to pass the data from controller to view. And, this will pass the data as a property of the object ViewBag. There is no need to typecast the data or do null checking. The scope of ViewBag will be to the current request only, the value of the ViewBag will be null while redirecting.

Example

Home.cs

Public ActionResult Index()  
{  
    ViewBag.Greetings = “Welcome Home”;  
    return View();  
}  

Index.cshtml

<h2>@ViewBag.Greetings</h2>  

ViewData

ViewData is a dictionary object that is used to pass the data from controller to view. And, this will be passed in the form of a Key-Value pair. In the ViewData typecasting is required to read the data in the view. If the data is complex then we need to check for the null to avoid the exception. The scope of ViewData will be as like ViewBag, it is permitted to the current request only, and the value of the ViewData will be null while redirecting.

Example

Home.cs

Public ActionResult Index()  
{  
    ViewData[”Greetings”] = “Welcome Home”;  
    return View();  
}  

Index.cshtml

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

TempData

TempData is a dictionary object that is used to pass the data from one action to another action of the same or different controller. And, TempData object will be stored in a session object. In the ViewData typecasting is required to read the data in the view. If the data is complex then we need to check for the null to avoid the exception. The scope of TempData is permitted to the next request only, and if we want Tempdata to be available even further, we should use Keep and peek.

Example

Home.cs

Public ActionResult Index()  
{  
    TempData[”Greetings”] = "Welcome Home”;  
    return View();  
}  

Public string GetMessage()  
{  
    return TempData[”Greetings”] ;  
}  

In general ViewBag, ViewData and TempData are basically used to pass data from action to view or action to another action, the scope varies from each other.

I hope this article will help you to understand how ViewData, ViewBag, and TempData work in MVC. We will be happy to help you if you have any issues or queries. Comment your suggestions and issues and we will try to resolve them.

What is your reaction?

0
Excited
0
Happy
0
In Love
0
Not Sure
0
Silly

You may also like

Comments are closed.

More in MVC