15 49.0138 8.38624 1 0 4000 1 https://codeisall.com 300
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 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 object ViewBag. There is no need to typecast the data or null checking. The scope of ViewBag will to the current request only, the value of the ViewBag will be null while redirecting.

Example

Home.cs

Index.cshtml

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, the value of the ViewData will be null while redirecting.

Example

Home.cs

Index.cshtml

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

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.

Share:
Category:MVC
PREVIOUS POST
Code-First Approach With ASP.NET MVC Project
NEXT POST
How to use Dapper ORM in C#