Tuesday, September 20, 2016

Persisting State in an ASP.NET MVC Web Application using TempData

When we think about persisting state in an ASP.NET MVC Web Application, most developers think of persistence using Session, Cache or Cookies, but many developers forget about using TempData as an easy means to persist information across ASP.NET MVC Requests!

Many developers frequently use the ViewBag and ViewData dictionary objects, but very few are aware of the TempData object.  The TempData object is especially handy when working with the PRG (Post Request Get) Pattern whereby you post from a controller method and then redirect to another controller method.

The problem with using objects such as ViewBag and ViewData is that they are only valid for that particular controller method request and will not be persistent across subsequent requests.  That is where TempData fits into the picture!

This MSDN article specifically addresses different methods for Passing Data in an ASP.NET MVC Application: https://msdn.microsoft.com/en-us/library/dd394711(v=vs.100).aspx

As you can see from the article, the usage of TempData is specifically geared towards "Passing State Between Action Methods"

You can read more about the TempData Dictionary object here: https://msdn.microsoft.com/en-us/library/system.web.mvc.tempdatadictionary(v=vs.118).aspx

This article also does a great job of explaining the differences between ViewData, ViewBag and TempData and their specific use case scenarios: http://rachelappel.com/when-to-use-viewbag-viewdata-or-tempdata-in-asp-net-mvc-3-applications/

No comments:

Post a Comment