Using Tempdata in ASP.NET MVC - Best Practice

I am using ASP.NET MVC 3 to build a web application.

What I'm trying to do is pass values ​​between two controllers, although there are many ways to do this. I am particularly interested in using TempData for this.

 public ActionResult Action1() { string someMessage; Test obj = SomeOperation(); if(obj.Valid) { someMessage = obj.UserName; } else { someMessage = obj.ModeratorName; } TempData["message"] = someMessage; return RedirectToAction("Index"); } public ActionResult Index() { ViewBag.Message = TempData["message"] return View(); } 

So is using TempData here? I mean, when using the best programming techniques, is this the right way to use TempData ?

When should you use TempData in real time?

Note: I looked at the following links

thank

+54
asp.net-mvc asp.net-mvc-3 asp.net-mvc-2
Sep 14 '12 at 10:44
source share
3 answers

TempData is a bucket in which you can dump data that is needed only for the next request. That is, everything that you put in TempData is discarded after the completion of the next request. This is useful for one-time messages, such as form validation errors. It is important to note that this applies to the next request in the session, so the request may occur in another browser window or tab.

To answer your specific question: there is no right way to use it. All this is up to convenience and convenience. If it works, it makes sense, while others understand it relatively easily, that’s good. In your particular case, passing a parameter this way is fine, but it is strange that you need to do this (smell of code?). I would prefer to store that value in resources (if it's a resource) or in a database (if it's a constant value). From your use, this seems like a resource, as you use it for the page title.

Hope this helps.

+58
Sep 14
source share
— -

Note that the behavior of saving TempData has changed in MVC 3, now the value in TempData is saved until it is read, and not just for the next request.

The TempData value is saved until it is read or until the session has run out of time. Persistent TempData in this way allows scripts such as redirection, since values ​​in TempData are available outside of a single query. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx

+36
Jun 30 '15 at 10:21
source share

Just remember saving TempData, it's a little complicated. For example, if you even just read TempData inside the current request, it will be deleted and therefore you do not have it for the next request. Instead, you can use the Peek method. I would recommend reading this cool article:

MVC Tempdata, Peek and keep the confusion

+11
Apr 20 '15 at 11:21
source share



All Articles