Despite no request tempdata[] getting wiped

Total Post:29

 1253  View(s)
Rate this:

TempData is supposed to persist for a subsequent request. However when I check the TempData in a subsequent controller I get a null. Why is TempData[] getting wiped off. Here are my two controllers. I am calling them in succession. So TempData[] should persist from one request to the next. Here is code from controller 1:

public ActionResult EditCampaign(int? Id)
    ViewBag.Banner = bannerText.Replace(" ", " ");
    // This is passed in case we need to add a new product or edit one. Then we'll
    // need the campaign id for reference purposes.
    TempData["campaign_id"] = Id;
    TempData["campaignBanner"] = bannerText.Replace(" ", " ");
    ViewBag.StartDate = debugger.startDate.ToShortDateString();
    ViewBag.EndDate = debugger.endDate.ToShortDateString();
    int Id1 = Convert.ToInt32(TempData["campaign_id"]);
    int convertedId1 = Id1
Here is where I try to get the value in Controller 2:
public ActionResult EditCampaign(CampaignDTO camps)
    // Do this up top. i.e. get the campaign ID
    camps.Id = Convert.ToInt32(TempData["campaign_id"]);
    string success = "";

I suspect that assigning the value of TempData in the penultimate line of controller 1 might be wiping off the data. If thats the case that is something new and not documented. Please help.

  1. Post:110

    Re: Despite no request tempdata[] getting wiped

    Reading the data is enough to remove it. Here's the relevant source:

    public object this[string key]
            object value;
            if (TryGetValue(key, out value))
                return value;
            return null;
            _data[key] = value;

    So in controller 1, when you say:

    int Id1 = Convert.ToInt32(TempData["campaign_id"]);

    you are actually removing the data you just inserted.

    There are many ways to work around this, but if you must read it from TempData, use Peek() instead.

    I hope you this will help you

      Modified On Apr-07-2018 12:23:01 AM