Erçin Dedeoğlu
Erçin Dedeoğlu

Reputation: 5383

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

Upvotes: 5

Views: 4622

Answers (2)

Andrew
Andrew

Reputation: 8674

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.

Upvotes: 3

MichaC
MichaC

Reputation: 13380

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...

Upvotes: 1

Related Questions