Difference Between ViewData and TempData?

Viewed 48273

I know what ViewData is and use it all the time, but in ASP.NET Preview 5 they introduced something new called TempData.

I normally strongly type my ViewData, instead of using the dictionary of objects approach.

So, when should I use TempData instead of ViewData?

Are there any best practices for this?

6 Answers

In one sentence: TempData are like ViewData with one difference: They only contain data between two successive requests, after that they are destroyed. You can use TempData to pass error messages or something similar.

Although outdated, this article has good description of the TempData lifecycle.

As Ben Scheirman said here:

TempData is a session-backed temporary storage dictionary that is available for one single request. It’s great to pass messages between controllers.

When an action returns a RedirectToAction result it causes an HTTP redirect (equivalent to Response.Redirect). Data can be preserved in the TempData property (dictionary) of the controller for the duration of a single HTTP redirect request.

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>
Related