I currently have a partial view that is called within my _Layout.cshtml, and is rendered throughout my whole MVC web application. It’s the first item at the top of the page to be rendered, and within the ActionResult method that is responsible for it, I have a call to my service to perform some business logic.
I originally put this service call in this particular ActionResult method as, still being new to MVC, I was falsely under the impression that it would get fired BEFORE any of the main page content, for each page across the site. However, I’ve just realised that the main view method is being called first, and this ChildActionOnly Method (for the Partial View) is being called afterwards.
Basically, it’s essential that the business logic call that Im currently making within the ChildActionOnly Method (associated with my partial view) is made BEFORE any other page processing is carried out (as I need to perform some DB updates upon each page load, which are then reflected in each requested page).
I’m happy to split this business logic out from the current partial views actionmethod, but am unsure where it should be going, or how I should be ensuring that it’s called before anything else, for each page request? What would be the norm approach?
You need a global action filter (luckily available starting MVC3).
See an example here:
http://weblogs.asp.net/gunnarpeipman/archive/2010/08/15/asp-net-mvc-3-global-action-filters.aspx
Copying from the sample (with slight modifications):
Applying in global.asax.cs (from the article):