Search code examples
asp.net-mvcasp.net-mvc-3action-filter

Instantiate a viewmodel in an action filter?


Q: How do I make an object that is instantiated inside an action-filter available within the action-method?

Background:

I have numerous forms (among other things) in an MVC web site.

Each has its own viewmodel, which inherits from a base type (FormPage).

My convention for these is to name the viewmodel type as the action-name prepended with "Form". So my ContactUs viewmodel is FormContactUs : FormPage.

A number of base viewmodel properties are set identically for all forms, and I have a generic utility functon that I call inside the action method to do this.

Setting the viewmodel, choosing the type based on the action-name and the naming convention, and setting base properties common to all forms from within an action-filter will make this just a bit DRY-er. My only hurdle appears to be figuring out how to make an object instantiated inside the filter available within the action-method.


Solution

  • Q: How do I make an object that is instantiated inside an action-filter available within the action-method?

    You could store it in the HttpContext.Items which is available throughout the entire request lifecycle. This being said, a custom model binder seems more adapted to your scenario than an action filter.