View Bag, View Data and Temp Data

What is ViewBag, ViewData and TempData in MVC

This Blog is regarding handling the data in MVC(MODEL,VIEW,CONTROLLER).  There are three ways of handling the data in MVC. they are
  1. ViewBag
  2. ViewData
  3. TempData 
1.ViewBag
ViewBag is a dynamic property. and used to pass data from controller to view
Value became null when redirection occurs
viewBag requires does not type casting
Example
In Controller
pulbic ActionResult Index()
{
        ViewBag.Name=“Mahesh”;
         return view();
}
In View Code
@ViewBag.Name
the result will be the Mahesh is displaying in the label
2.ViewData
ViewData is directory of object that is derived from ViewDataDirectory.
It will move  data from Controller to View
we can pass data as collection
it is accessible string as a key
ViewData requires typecasting
The code in the Controller is
public ActionResult Index()
{
      ViewData[“Name”]=“Mahesh”;
       return View();
}
in the View
@ViewData[“Name”]
the result will be the Mahesh 
Similarities between the ViewBag and ViewData
1.maintain data while Moving Data from Controller to View
2.Pass data from controller to corresponding view
3. sort life value will be null while redirection will occur
3.TempData
TempData is a directory derived from TempDataDirectory and stored string as akey and object value
help to maintain the data to move from controller to controller to controller or from action to action
The data will maintain on redirections
In Controller the code is
public ActionResult Index()
{
     var model=new Employee()
     {
      Name=“mahesh”,
      ID=1
      };
      TempData[“Employee”]=model;
      Rerturn RedirectToAction(“Employee”);
}
public ActionResult Employee()
{
       var model=TempData[“Employee”];
       return view(model)
}

Popular Posts