2

The Attach method is an ajax call made to change the variable stored inside TempData so that when the user refreshes the Index page the changes to persist. !

I tried initializing the TempData inside the constructor of the controller but the TempData object is null at that time.Where is TempData initialized and how can i populate it before any Action if not in constructor?

P.S I have also tried to maintain state by using a static variable (before TempData) but it does not work.

class MyController
{
            public LocationController(TreasureContext con)
            {
                TempData.Put<string>("checkboxesState","enabled"); //tempdata is null here
                this.context = con;
            }

            [HttpGet]
            public IActionResult Index() 
            {   
                ViewData["tstory"]=JsonConvert.SerializeObject(TempData.Get<Story>("tstory"));
                ViewData["checkboxesState"]=JsonConvert.SerializeObject(TempData.Get<string>("chkState")); //tempdata value is sent to the view to set some checkboxes 
                if(ViewData["tstory"]!=null)
                {
                ViewData["tlocations"]=JsonConvert.SerializeObject(TempData.Get<IEnumerable<long>>("tlocations"));
                TempData.Keep();
                return View(context.Locations);
                }
                return RedirectToAction("Index","Story");
             }
}


        [HttpPost, ActionName("Attach")]
        public bool Attach([FromBody]List<Location> locations)
        {

                this.TempData.Put<string>("chkState",Constants.JS.CbxDisabled);
                return true; 
        }

Tempdata extensions:

public static void Put<T>(this ITempDataDictionary tempData, string key, T value)
        {
            tempData[key]=JsonConvert.SerializeObject(value);
        }
        public static T Get<T>(this ITempDataDictionary tempData, string key) where T : class
        {
        object o;
        tempData.TryGetValue(key, out o);
        return o == null ? null : JsonConvert.DeserializeObject<T>((string)o);
        }
Ivin Raj
  • 3,448
  • 2
  • 28
  • 65
Bercovici Adrian
  • 8,794
  • 17
  • 73
  • 152

0 Answers0