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.

1
  • 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. Commented Oct 28, 2013 at 19:59

1 Answer 1

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();
 }
Sign up to request clarification or add additional context in comments.

3 Comments

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.
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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.