0

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.

1
  • 2
    @TempData["Msg3"] in the view will not have a value (TempData only lasts one request). But @TempData["Msg4"] should have a value - are you saying that is also null? Commented Aug 21, 2017 at 10:01

2 Answers 2

4

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"];
Sign up to request clarification or add additional context in comments.

Comments

-3

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"]; 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.