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):
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:
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.
4 Responses to “How to avoid duplicate data fecthing with ASP.NET MVC”
Sorry, the comment form is closed at this time.
[...] to VoteHow to avoid duplicate data fecthing with ASP.NET MVC (5/3/2009)Sunday, May 03, 2009 from mookid.dkIn this post I would like to show a simple trick on how to avoid [...]
How to avoid duplicate data fecthing with ASP.NET MVC – Mogens Heller Grabe…
Thank you for submitting this cool story – Trackback from DotNetShoutout…
[...] you read my previous post and you thought to yourself: “but that’s a violation of DRY!”, then please stop [...]
[...] How to avoid duplicate data fecthing with ASP.NET MVC [...]