Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.NET MVC, ActionFilters, static classes and passing data around

I'd like to hear your opinions and maybe better suggestions for the following scenario:

I have define a custom ActionFilter that does some job and comes out with some value. I would like to use that value in controller actions and in models.

Now, I could use TempData to pass this value from the ActionFilter to any controller action method, then distribute this value over to all models that get passed to returned views.

I'm sure it will work but this TempData will be there in session where and when nobody actually needs it anymore. The value is supposed to be used exclusively in the code during the time of a single request after which it effectively invalidates.

I have come up with two options:

  1. In ActionFilter, I set this value in TempData in OnActioExecuting() and I remove it in OnActionExecuted(). Do I understand it correctly that by the time OnActionExecuted is called, the controller action has finished, the response has already been generated and this TempData content hasn't made its way to the session YET?

  2. In any of my custom static classes (logic) I just define a public property for this value and I use it whenever needed. Will this static field not be lost between OnActionExecuting() and actually executing the controller method? Are there any other issues with possible loosing this value during the request processing on the server?

Are there any other/better options I havem't considered yet?

like image 612
User Avatar asked May 03 '09 19:05

User


1 Answers

I have found that using ActionParameters makes your code very easily testable. You can do it like so:

// inside your actionfilter
public override void OnActionExecuting(ActionExecutinContext context)
{
    var someData = // ... load some data

    context.ActionParameters["someData"] = someData;
}


// and then in your action method
[ProvideSomeData]
public ViewResult Index(SomeData someData)
{
    // someData will be populated in here
}
like image 187
mookid8000 Avatar answered Sep 18 '22 12:09

mookid8000