view data is used when we want to pass data from controller to corresponding view.
view data have very short life it means it will destroy when redirection occurs.
Example(Controller):
public ViewResult try1()
{
ViewData["DateTime"] = DateTime.Now;
ViewData["Name"] = "Mehta Hitanshi";
ViewData["Twitter"] = "@hitanshi";
ViewData["City"] = "surat";
return View();
}
try1.cshtm
<table>
<tr>
<th>Name</th>
<th>Twitter</th>
<th>Email</th>
<th>City</th>
<th>Mobile</th>
</tr>
<tr>
<td>@ViewData["Name"]</td>
<td>@ViewData["Twitter"]</td>
<td>@ViewData["City"]</td>
</tr>
</table>
TempData transfers the data between controllers or between actions.
It is used to store one time messages and its life is very short.we can use TempData.Keep() to make it available through all actions or to make it persistent.
Example(Controller):
public ActionResult try3()
{
TempData["DateTime"] = DateTime.Now;
TempData["Name"] = "Ravina";
TempData["Twitter"] = "@silentRavina";
TempData["Email"] = "Ravina12@gmail.com";
TempData["City"] = "India";
TempData["MobNo"] = 9998975436;
return RedirectToAction("TempView1");
}
public ActionResult TempView1()
{
return View();
}
TempView1.cshtm
<table>
<tr>
<th>Name</th>
<th>Twitter</th>
<th>Email</th>
<th>City</th>
<th>Mobile</th>
</tr>
<tr>
<td>@TempData["Name"]</td>
<td>@TempData["Twitter"]</td>
<td>@TempData["Email"]</td>
<td>@TempData["City"]</td>
<td>@TempData["MobNo"]</td>
</tr>
</table>