31

I'm trying to crate a custom action filter attribute. And some where, I need facilities, such us TempData[key] and TryUpdateModel... My custom attribute class deriving from the ActionFilterAttribute, I can access both below methods.

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
}
public override void OnResultExecuted(ResultExecutedContext filterContext)
{
}

Unfortunately, from both filtercontext local variables, I don't know how to access the TempData. I've tried to follow several leads, but without success. After all, maybe there's TempData in the filterContext variables. In that case, how do I access the TemData available?

Thanks for helping

Arithmomaniac
  • 4,604
  • 3
  • 38
  • 58
Richard77
  • 20,343
  • 46
  • 150
  • 252

1 Answers1

56
var foo = filterContext.Controller.TempData["foo"];
Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • Thanks a lot. That was rather easy. Just one last question. Which controller are we talking about here? the one that sent the request or the one that contains the method my custom attribute is supposed to decorate? The reason I'm asking that is ... What if I need to access method such us TryUpdateModel() from my custom attribute, How do I do that? – Richard77 Nov 23 '10 at 10:03
  • It's the one that contains the action decorated with your custom attribute. – Darin Dimitrov Nov 23 '10 at 10:59
  • Then how do I access its facilities such as TryUpdateModel? – Richard77 Nov 23 '10 at 11:11
  • TryUpdateModel is a protected method meaning that you can only use it in a controller action. It is not intended to be used in an action filter and this is not possible. So maybe start by explaining what you are trying to do. You can directly access the action parameters (`filterContext.ActionParameters`) and this way you shouldn't ever need to use TryUpdateModel. Personally I always use action parameters and never use TryUpdateModel. – Darin Dimitrov Nov 23 '10 at 12:01
  • Well, the unique point of trying to access TryUpdateModel was to be able to update an object model that I don't even know in advance. This question is related to an other question I posted yesterday. I didn't get much of an answer so I suspected that I didn't formulated it the right. So, I'm trying to understand first the subject so that I can update the question. – Richard77 Nov 23 '10 at 12:34
  • Here's the link to my yesterday question/ http://stackoverflow.com/questions/4245555/need-to-transfert-some-functionalities-from-a-controller-to-an-attribute-so-they – Richard77 Nov 23 '10 at 12:35