April 2, 2015

MVC Action Filters and the Case of the Russian Dolls

MVC Action Filters are a great way to add functionality that will run on every request.

However they can be a little tricky and have some unwanted side affects when using child actions via Html.Action.

The problem is that Action Filters will run multiple times by default when called via Html.Action. Once for the original action and then another time for each of the child actions. To prevent this from happening you need to ensure that the action filter is only called for the original action and not for the subsequent child actions. You can detect this situation by checking the filterContext.IsChildAction property.

So to properly handle the situation first check if the action is a child action and if it is not then run your code as normal. If it is a child action then do not run your code. Here is a simple example:


No comments:

Post a Comment

Your feedback is appreciated!