ViewBag
– ViewBag is used to send a small amount of data to the view.– There may be some situation where you want to transfer some temporary data to view which is not included in the model object.
– The viewBag is a dynamic type property of ControllerBase class.
– It does not retain value when redirection occurs,it is available only for Current Request.
– ViewBag is a dynamic property and it makes use of the C# 4.0 dynamic features.
public class DemoController : Controller
{
IList CarList = new List() {
new Car(){ CarName=”i10″, CarColor=”Black”,CarMileage=18.2 },
new Car(){ CarName=”EON”, CarColor=”Silver”, CarMileage=18.2 },
new Car(){ CarName=”Swift”, CarColor=”Red”, CarMileage=18.2},
new Car(){ CarName=”Verna”, CarColor=”Black”, CarMileage=18.2},
new Car(){ CarName=”Ciaz”, CarColor=”Silver”, CarMileage=18.2}
};
public ActionResult Index()
{
ViewBag.TotalCar = CarList.Count();
return View();
}
}
ViewData
– ViewData is similar to ViewBag, It can be used to send data from controller to view.– It is a dictionary , which possese key-value pairs, where each key must be string.
– Viewdata last long only for current http request.
public class DemoController : Controller
{
public ActionResult Index()
{
ViewData[“Simple”] = “This string is stored in viewData.”;
return View();
}
}
To get back value from viewData write below line in view.
@ViewData[“Simple”]
TempData
– TempData retain value across subsequent HTTP Request– It can be use to maintain data between controller actions as well as redirects.
– It internally stores data in session but it get destroyed earliar than session.
In the below example, a string value is stored in the TempData object in JupiterController
and it is redirected to EarthController and finally it is displayed in View.
public class JupiterController : Controller
{
// GET: First
public ActionResult Index()
{
TempData[“Message”] = “Jupiter is largest planet in solar system”;
return new RedirectResult(@”~\Earth\”);
}
}
public class EarthController : Controller
{
// GET: Second
public ActionResult Index()
{
return View();
}
}
View of EarthController
<html>
<head>
<meta name=”viewport” content=”width=device-width”/>
<title>Solar System</title>
</head>
<body>
<div>
@TempData[“Message”];
</div>
</body>
</html>