Chris
Chris

Reputation: 8412

At what point in Controller execution is TempData populated

I have a base class for my controllers. In the constructor of the base class I was trying to populate a ViewBag property from TempData. However it seems that TempData is not populated at that point, nor is it in the OnBeginExecute method.

I need to populate this ViewBag property in the base class, as all controllers need the same variable (it's a redirection message).

Which override of Controller in my base class can I use to do this?

Upvotes: 1

Views: 1597

Answers (2)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038710

TempData as well as any HttpContext related stuff is not available in the controller constructor. You can use them starting from the Initialize method. So if you need to populate them in a global manner for a controller either override this method or write a custom action filter and decorate your controller with it:

public class HomeController: Controller
{
    protected override void Initialize(RequestContext requestContext)
    {
        base.Initialize(requestContext);
        // now you can access the HttpContext
    }

    ...
}

Upvotes: 5

Kevin Aenmey
Kevin Aenmey

Reputation: 13419

Take a look at BeginExecuteCore:

protected override IAsyncResult BeginExecuteCore(AsyncCallback callback, object state)
{
    // TempData is not populated here
    var result = base.BeginExecuteCore(callback, state);
    // TempData is populated here

    return result;
}

Upvotes: 2

Related Questions