Reputation: 1
I am learning ASP.net MVC5 with the code in book.
public ActionResult DemoTempData()
{
ViewData["Msg1"] = "From ViewData Message.";
ViewBag.Msg2 = "From ViewBag Message.";
TempData["Msg3"] = "From TempData Message.";
return RedirectToAction("Redirect1");
}
public ActionResult Redirect1()
{
TempData["Msg4"] = TempData["Msg3"];
return RedirectToAction("GetRedirectData");
}
public ActionResult GetRedirectData()
{
return View();
}
GetRedirectData
view:
@{
ViewBag.Title = "GetRedirectData";
}
<h2>GetRedirectData</h2>
<ul>
<li>ViewData-Msg1:@ViewData["Msg1"]</li>
<li>ViewBag-Msg2:@ViewBag.Msg2</li>
<li>TempData-Msg3:@TempData["Msg3"]</li>
<li>TempData-Msg4:@TempData["Msg4"]</li>
</ul>
I know that ViewData
and ViewBag
will not pass value.
The Msg3
and Msg4
in view should have value, but it doesn't.
I check the value in Redirect1()
, it turns out that Msg3
is null
.
I am very confused with what's going on.
Upvotes: 0
Views: 2330
Reputation: 546
in the controller Use the builtin Session plumbing, it stays with you until you destroy it. I like it because it always works, and its easy. It is available in
System.Web.HttpContext
which is really the current request
to save use (Example)
System.Web.HttpContext.Current.Session["Msg3"] = StringOfIds;
To retrieve...
string msg3= (string) System.Web.HttpContext.Current.Session["Msg3"];
Upvotes: -3
Reputation: 1355
ASP.NET MVC TempData stores it’s content in Session state. So TempData gets destroyed immediately after it’s used in subsequent HTTP request.
In your case you are assigning the TempData["Msg3"] to TempData["Msg4"]. So once you consume the content from TempData["Msg3"] it gets destroyed. So whenever you try to access TempData["Msg3"] you get null value.
The Peek and Keep methods allow you to read the value without getting destroyed.
reference :
https://msdn.microsoft.com/enus/library/system.web.mvc.tempdatadictionary.peek(v=vs.118).aspx
object value = TempData["value"];
TempData.Keep("value");
object value = TempData["value"];
Upvotes: 4