Monday, 4 September 2017

What Is ViewData And ViewBag In MVC- Difference With Example

Introduction
In this article we will learn what is viewdata and viewbag. How to use ViewData in mvc. How to use ViewBag in MVC. ViewData and ViewBage example in mvc. Difference etween Viewdata and ViewBag in mvc.

Both ViewData and ViewBag is used to store the data In Asp.Net MVC and transfer the data from controller to View.

ViewData is nothing but a dictionary of objects and it is accessible by string as key. ViewData is a property of controller that exposes an instance of the ViewDataDictionary class.It is available for the current request only. If any redirection happens then its value become null.
public ActionResult Index()
{
    ViewData["UName"] = "GurujiPoint.com";
    return View();
}

ViewBag is a dynamic property (dynamic keyword which is introduced in .net framework 4.0). ViewBag is able to set and get value dynamically and able to add any number of additional fields without converting it to strongly typed. It is available for the current request only.  If any redirection happens then its value become null.ViewBag is just a wrapper around the ViewData.
public ActionResult Index()
{
    ViewBag.UName= "GurujiPoint.com";
    return View();
}

Difference between ViewData and ViewBag
ViewData
ViewBag
It is Key-Value Dictionary collection
It is a type object
ViewData is a dictionary object and it is property of ControllerBase class
ViewBag is Dynamic property of ControllerBase class
ViewData is Faster than ViewBag
ViewBag is slower than ViewData
ViewData also works with .net framework 3.5 and above
ViewBag only works with .net framework 4.0 and above
ViewData is introduced in MVC 1.0 and available in MVC 1.0 and above
ViewBag is introduced in MVC 3.0 and available in MVC 3.0 and above
Type Conversion code is required while enumerating
In depth, ViewBag is used dynamic, so there is no need to type conversion while enumerating
Its value becomes null if redirection has occurred
Same as ViewData
It lies only during the current request.
Same as ViewData.

No comments:

Post a Comment