a blog for those who code

Wednesday, 31 August 2016

Difference between ViewBag and ViewData

In this post we will be discussing about difference between ViewBag and ViewData in MVC. In MVC you can pass data from controller to view using both ViewBag and ViewData. So both ViewData and ViewBag helps you to move data from controller to view. But neither of them can be used to pass data from view to controller. The value will become null when redirection occurs.

ViewBag is a wrapper around the older ViewData. ViewBag takes advantage of the new dynamic features called dynamic typing of C# 4.0 which allows you dynamically add properties on to an object at run-time. Whereas ViewData is a dictionary of objects that is derived from ViewDataDictionary class and is accessible using strings as keys.

One key difference between ViewBag and ViewData is that ViewBag does not require typecasting for complex data type whereas ViewData requires typecasting for complex data type. In ViewData you need to explicitly check for null values to avoid error but in ViewBag you need not have to check for null values.

// Setting View Bag Property
ViewBag.MyNewProperty = "Dynamic Property";

// Setting View data Property
ViewData.Add(new KayValuePair<string, object>("MyProperty", "View Data property"));

ViewBag in Action method

public ActionResult Index()
  ViewBag.Myproperty = "Hello World";
  return View();

ViewData in Action method

public ActionResult Index()
  ViewData["MyProperty"] = "Hello World";
  return View();

ViewData and ViewBag in Razor View


ViewData and ViewBag both use the same dictionary internally. So that means ViewData Key should not match with the property name of ViewBag if you are using both in your application otherwise it will throw a run-time exception.

ViewBag.Myproperty = "Hello World";
ViewData["MyProperty"] = "Hello World"; // Gives Error

Please Like and Share the CodingDefined Blog, if you find it interesting and helpful.

No comments:

Post a Comment

Contact Us


Email *

Message *


Best Hosting Plans

CC License