I am using ASP.NET MVC 3 to build a web application.
What I am trying to do is pass values between two controllers, though there are many ways to do this I am particular 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 the use of TempData
here correct ? I mean under best programming practices is this correct way of using TempData
?
In what real time cases should TempData
be used ?
Note : I have gone through the following links
Thanks
This question is related to
asp.net-mvc
asp.net-mvc-3
asp.net-mvc-2
tempdata
Just be aware of TempData persistence, it's a bit tricky. For example if you even simply read TempData inside the current request, it would be removed and consequently you don't have it for the next request. Instead, you can use Peek
method. I would recommend reading this cool article:
Please note that MVC 3 onwards the persistence behavior of TempData has changed, now the value in TempData is persisted until it is read, and not just for the next request.
The value of TempData persists until it is read or until the session times out. Persisting TempData in this way enables scenarios such as redirection, because the values in TempData are available beyond a single request. https://msdn.microsoft.com/en-in/library/dd394711%28v=vs.100%29.aspx
Source: Stackoverflow.com