views:

24

answers:

1

Hi,

I need some data to be available on all the viewpages inside the website. The data comes from an parameter supplied to all the routes, i want to get that param and get the according data for it and make it available for all the views (including the master pages).

It would be nice if it could be done in one place.

What do i need to do to get that functionality, can it even be done?

Greetz, Richard.

A: 

The easiest (may not be the best) would be to write a base Controller class that

1) handles one of the following events to do the job:

  • OnActionExecuted
  • OnActionExecuting
  • OnResultExecuted
  • OnResultExecuting

2) Sets the data you want to have available in ViewData.

3) Use the ViewData from your views.

4) All your Controllers must inherit from your custom base Controller.

This might not be the nicest of all approaches as I usually try to avoid inheritance like the plague, but it will work. Other options.

1) Implement it in an ActionFilter and make sure add the attribute to all ActionMethods.

2) Use something like MVC Turbine to define ActionFilter's that trigger for all ActionMethods in you ASP.NET MVC Application.

Roberto Hernandez
Thanks, the problem with viewdata is that it is not typed so i have to cast it everytime i need the data. Is there a solution for that?
Richard
The MVCContrib project might be of help, as they have written a set of Extensions that allow you to extract data from ViewData (IDictionary<string,Object>) in a strongly typed fashion. http://mvccontrib.codeplex.com/documentation?referringTitle=Home
Roberto Hernandez