DESPITE NO REQUEST TEMPDATA[] GETTING WIPED

Maria Susan

Total Post:29

Points:107
Posted by  Maria Susan
 1037  View(s)
Ratings:
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:

[HttpGet]
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:
[HttpPost]
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. Jayden Bell

    Post:110

    Points:774
    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]
    {
        get
        {
            object value;
            if (TryGetValue(key, out value))
            {
                _initialKeys.Remove(key);
                return value;
            }
            return null;
        }
        set
        {
            _data[key] = value;
            _initialKeys.Add(key);
        }
    }

    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

Answer

NEWSLETTER

Enter your email address here always to be updated. We promise not to spam!