Tech News

What is ViewBag & ViewData ?

ASP.NET MVC offers us three options ViewData, VieBag and TempData for passing data from controller to view and in next request.ViewData and ViewBag are almost similar and TempData performs additional responsibility. you’ll use the ViewData, ViewBag, and TempData objects for the purposes of transporting small amounts of data from and to specific locations (e.g., controller to view or between views). Both the ViewData and ViewBag objects work well in the following scenarios:
  • Incorporating dropdown lists of lookup data into an entity
  • Components like a shopping cart
  • Widgets like a user profile widget
  • Small amounts of aggregate data
Similarities between ViewBag & ViewData :
  1. Helps to maintain data when you move from controller to view.
  2. Used to pass data from controller to corresponding view.
  3. Short life means value becomes null when redirection occurs. This is because their goal is to provide a way to communicate between controllers and views. It’s a communication mechanism within the server call.
Difference between ViewBag & ViewData:
  1. ViewData is a dictionary of objects that is derived from ViewDataDictionary class and accessible using strings as keys.
  2. ViewBag is a dynamic property that takes advantage of the new dynamic features in C# 4.0.
  3. ViewData requires typecasting for complex data type and check for null values to avoid error.
  4. ViewBag doesn’t require typecasting for complex data type.
ViewBag & ViewData Example:


public ActionResult Index()
{
    ViewBag.Name = "Monjurul Habib";
    return View();
}

public ActionResult Index()
{
    ViewData["Name"] = "Monjurul Habib";
    return View();
} 
In View:

@ViewBag.Name 
@ViewData["Name"] 
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
0
Would love your thoughts, please comment.x
()
x