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):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
public class ProvideCurrentUserViewModelAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext context) { var sessionContext = ServiceLocator.Resolve<ISessionContext>(); var currentUser = sessionContext.CurrentUser; context.ActionParameters["currentUser"] = new CurrentUserViewModel(currentUser); } public override void OnActionExecuted(ActionExecutedContext context) { } } |
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:
1 2 3 4 5 6 7 8 9 10 11 |
public class HomeController : Controller { [ProvideCurrentUserViewModel] public ViewResult Index(CurrentUserViewModel currentUser) { return View(new HomeScreenViewModel { CurrentUser = currentUser }); } } |
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”