Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing to TempData From GLOBAL.ASAX

I'am looking for a method to get access and set TempData in GLOBAL.ASAX

I tried like this but still getting Error on TempData.

HttpContext.Current.TempData["Passed"] = "1";

like image 298
Erçin Dedeoğlu Avatar asked Oct 02 '22 20:10

Erçin Dedeoğlu


2 Answers

TempData is a property of the System.Web.Mvc.ControllerBase class. Since you are not in a controller, it is not accessible. I would highly doubt you can get at it easily, since the whole chain that sets this up is constructed by the MVC framework.

Since TempData[] is backed by the Session (i.e. SessionStateTempDataProvider) you should be able to insert the value into session and get it out. This does rely on reading the source code (to find the key used), and definitely isn't supported.

var dataKey = "__ControllerTempData";
var dataDict = HttpContext.Current.Session[dataKey] as IDictionary<string,object>;
if (dataDict == null) { 
    /* what do you want to do? add a new IDict<> and put in session? */ 
} else {
    dataDict["Passed"] = 1;
    HttpContext.Current.Session[dataKey] = dataDict;
}

Caveat, untested code! You WILL need to debug.

As others have said, what is the reason for doing this? What are you trying to accomplish? The is probably a much better way to do it.

like image 172
Andrew Avatar answered Oct 05 '22 10:10

Andrew


Thats obviously not working because HttpContext does not have any property called TempData.

Depending of what you want to achieve, use HttpContext.Current.Cache or HttpContext.Current.Session for example...

like image 31
MichaC Avatar answered Oct 05 '22 10:10

MichaC