If you read my previous post and you thought to yourself: “but that’s a violation of DRY!”, then please stop whining right away!

If you – like me – like to make your dependencies explicit, you will probably think that it is perfectly fine to have to do the following things every time you want to have a piece of data automatically supplied for you:

  1. Apply the attribute to the action method (can be omitted if it has already been applied at the controller level)
  2. Change the signature of the action method
  3. Make sure the data makes its way into the view model handed to your view

In my opinion this is a fair compromise between avoiding writing code and still being explicit about what is going on.

If you, however, feel that there are too many steps above, and you want stuff to happen more automagically, you can do it in another way, that I find almost as attractive… first, create an interface to apply to all view models, that are capable of holding this piece of data – e.g. like this:

Then, make your page level view model implement this interface – from my previous example:

And then modify the action filter to fetch the data in OnActionExecuting and insert the view model for you in OnActionExecuted – like so:

This way, at most two things need to be done to automatically provide a piece of view data:

  1. Make the page level view model implement an appropriate interface (can be omitted if it already implements it)
  2. Apply the attribute to the action method (can be omitted if it has already been applied at the controller level)

It is definitely more DRY, but its lack of verbosity makes it harder to understand. And here, I don’t mean “understand” as in “haha, Mogens is too stupid to understand what is going on” – my point is that I will be wasting a few more brain cycles the next time I look at this action method while trying to figure out how it worked.

Another way to avoid duplicate data fetching with ASP.NET MVC

Leave a Reply

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

%d bloggers like this: