How to avoid duplicate data fecthing with ASP.NET MVC

One of the things I like about ASP.NET MVC is that there are so many ways to do everything. I.e. the framework is pretty un-opinionate. This, of course, can also be a serious drawback, because there will more bad snippets on the ‘net where people do ugly stuff in non-preferred ways. And sometimes it is hard to figure out if the way you’re doing something is actually the best for you.

In this post I would like to show a simple trick on how to avoid duplicate data fetching with ASP.NET MVC. That is, how can you avoid typing the same data fecthing logic in every controller action when a piece of data must be available to more than one action method.

In ASP.NET MVC it is actually very easy: use an action filter attribute, and have the filter load the data in the OnActionExecuting method. For example something like this (assuming that you have an ISessionContext that provides information about the currently logged-in user):

This way, if you apply this attribute at either the controller or the controller action level, a new action parameter will automatically be available for you to use. A simple example could be something like this:

By providing the data through the ActionParameters dictionary of the filter context, you can be explicit about which pieces of data will be available inside every controller action.

2 thoughts on “How to avoid duplicate data fecthing with ASP.NET MVC

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.