2

I set a property in the base controller so that I can have access to its value from every action. Originally I put code to get the value (from a cookie) in the OnActionExecuting method, which works, but then I realized it's going to get called on every action call (some pages may run it hundreds of times because of repeating partial views). How could I do it so it's only called once per page?

I looked at a similar answered question... How to call a function *only once* in ASP.NET MVC page cycle but the answer only deals with Ajax requests, which is not my problem.

Community
  • 1
  • 1
Rodolfo
  • 4,155
  • 23
  • 38
  • What do you mean by "once per page"? You do realize that a new controller instance is [generally] created each time a GET or POST request is made, don't you? You could use a `static` property, but that will be invoked once per app domain. To set it once per user session, consider using a session state variable. – Nicholas Carey Oct 28 '13 at 19:59

1 Answers1

1

Similar to @philsandler mentioned you can use the same solution. BUT I would still use an Action Filter to make it reusable and contained. Something like below.

public class RunOnlyPerAction : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext) {
        if (!filterContext.HttpContext.Request.IsAjaxRequest())
        {
            //read cookie
        }
    }
}


 [RunOnlyPerAction]
 public ActionResult Index()
 {
     return View();
 }
Spock
  • 7,009
  • 1
  • 41
  • 60
  • but it's not an ajax request, I have pages that contain partial views and they're displayed on the 'parent' view with a `@html.action(xxx)` for example. – Rodolfo Oct 28 '13 at 19:54
  • I think my question didn't make much sense now that I'm reading it again. I'm thinking I could do what I want with an action filter so marking this as answer. – Rodolfo Oct 28 '13 at 20:10
  • Is this related? http://stackoverflow.com/questions/28078534/asp-net-mvc-lifecycle-once-per-page-request – Michael R Jan 21 '15 at 23:15