Introduction: In this
article today I am going to explain what is the difference between ViewBag, ViewData
and TempData in mvc
We
use the ViewData, ViewBag and TempData to pass data from controller to view. ViewBag
and ViewData are almost similar.
ViewData:
ViewData
is a dictionary object that is derived from ViewDataDictionary class and
accessible using strings as key values. It is used to pass data from controller
to view. It requires typecasting for a complex data type and check for null
values to avoid error. ViewData has short life because its life lies during
current request only. If redirection occurs its value become null. ViewData is
faster than ViewBag.
Example:
Controller:
public ActionResult Index()
{
ViewData["Username"] = "Vijay Saklani";
ViewData["PhoneNo"] = "1233456654";
return
View();
}
View:
@{
ViewBag.Title = "Index";
}
<h2>View data Example</h2>
<p>User Name : @ViewData["Username"]</p>
<p>Phone Number : @ViewData["PhoneNo"]</p>
Output:
ViewBag:
ViewBag
is a dynamic property that takes advantage of the new dynamic features in C#
4.0. ViewBag is also used to pass data from the controller to view. It does not
required typecasting to get complex data. ViewBag also has short life means its
life lies only during current request only.If redirection occurs its value
become null. ViewBag is slower than ViewData.
Example:
Controller:
public ActionResult Index()
{
ViewBag.Username = "Vijay";
ViewBag.Phoneno
= "123456789";
return View();
}
View:
@{
ViewBag.Title = "Index";
}
<h2>Viewbag Example</h2>
<p>User Name: @ViewBag.username</p>
<p>Password: @ViewBag.phoneno</p>
Output:
TempData:
TempData
is also a dictionary object derived from TempDataDictionary class and stored in
short lives session. It is a string key and object value. TempData is used to
pass data between current and next subsequent request only. Means it helps to
maintain the data when you move from one controller to other controller or from
one action to other action. It requires typecasting for complex data type and
check for null values to avoid error. It is mostly used to store one time
messages like Validation, Error Messages etc.
Example:
Controller:
public ActionResult Userdetail()
{
TempData["Message"] = "TemData Example";
return
RedirectToAction("Index");
}
View:
@TempData["Message"]
Output:
When
we go to view Userdetail it redirect us to the Index show the message.
No comments:
Post a Comment