5
Reply

What is the difference between ViewData, ViewBag and TempData?

Manoj Bhoir

Manoj Bhoir

9y
2.1k
1
Reply

    ViewData: 1.ViewData is a dictionary object and it is property of ControllerBase class 2.ViewData is Faster than ViewBag 3.Its value becomes null if redirection has occurred. ViewBag: 1.ViewBag is Dynamic property of ControllerBase class. 2.ViewBag is slower than ViewData 3.Same as ViewDataTempdata: 1.TempData is a dictionary object and it is property of controllerBase class. 2.NA 3.TempData is used to pass data between two consecutive requests

    ViewData contains the key, value pairs as dictionary and this is derived from class: "ViewDataDictionary". In action method we are setting the value for ViewData and in view the value will be fetched by typecasting. ViewBag is a wrapper around ViewData, which allows to create dynamic properties. Advantage of viewbag over viewdata will be: In ViewBag no need to typecast the objects as in ViewData.ViewBag will take advantage of dynamic keyword which is introduced in version 4.0. But before using ViewBag we have to keep in mind that ViewBag is slower than ViewData. TempData is again a key, value pair as ViewData. This is derived from "TempDataDictionary" class. TempData is used when the data is to be used in two consecutive requests, this could be between the actions or between the controllers. This requires typecasting in view.

    Hi pls ref below link and strong your knowledge http://www.codeproject.com/Articles/866143/Learn-MVC-Project-in-days-Day

    Hi pls ref below link and strong your knowledge http://www.codeproject.com/Articles/866143/Learn-MVC-Project-in-days-Day

    In order to pass data from controller to view and in next subsequent request, ASP.NET MVC framework provides different options i.e. ViewData, ViewBag and TempData.Both ViewBag and ViewData are used to to communicate between controller and corresponding view. But this communication is only for server call, it becomes null if redirect occurs. So, in short, its a mechanism to maintain state between controller and corresponding view. ViewData is a dictionary object while ViewBag is a dynamic property (a new C# 4.0 feature). ViewData being a dictionary object is accessible using strings as keys and also requires typecasting for complex types. On the other hand, ViewBag doesn't have typecasting and null checks.TempData is also a dictionary object that stays for the time of an HTTP Request. So, Tempdata can be used to maintain data between redirects i.e from one controller to the other controller.