We have a white-labelled platform built on Asp.Net MVC2. At present the site has 6 controllers, as well as all the core views etc that can enable it to work straight out of the box. So far we’ve built 5 sites from it and it’s all been great.
Now, however, I have a requirement that means I need to be able to pass a new piece of data (in the ViewData dictionary will be fine) to all views from any action. This data is seeded from query string and then from a cookie.
One of the primary reasons for this is to be able to add an extra image to the site’s master page depending on this data’s value. I could of course be really dirty and place the deserialization code in the master page; but I’d rather find a way to ensure that it gets added to the ViewData for every request that doesn’t involve controller inheritance and action method overriding(!).
Any ideas greatly greatly appreciated!
You could write a custom action filter attribute and apply this attribute to a base controller or all actions that need to have this information injected:
And then decorate your base controller with this attribute:
In ASP.NET MVC 3 there’s a notion of global action filters so that you don’t even need to have a base controller or decorate all your actions with this filter. There’s a workaround allowing you to achieve the same in ASP.NET MVC 2. Now all your views get this additional property in the view data.
This being said, the previous is an ugly workaround and not something I would recommend (ViewData is ugly). You may take a look at Html.Action and Html.RenderAction helpers. Here’s how this might look:
Then have some strongly typed partial which will contain the required HTML (
~/Views/MySpecial/Index.ascx) and finally include this in your master page: