tags:

views:

99

answers:

2

I want to get a value from the user session and display it in the site.master file. How can I do this so that every view page has this value? Do I have to place ViewData["MyValue"] in every controller action? Is there a global way of doing this in one place so I don't have to have the same code in every controller action?

+3  A: 

You could write an action filter attribute and decorate your controller with it:

public class CustomFilterAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        base.OnActionExecuted(filterContext);
        filterContext.Controller.ViewData["MyValue"] = "some value";
    }
}

And then decorate the controller with this attribute:

[CustomFilter]
public class MyController: Controller
{
    // actions
}

This will ensure that ViewData["MyValue"] will be set on all action belonging to this controller.

Darin Dimitrov
do you have an example of this?
Joe
Further to this, you could have your own `BaseController` with the `CustomFilter` attribute which all your individual controllers inherit from. This will mean you only have to have it in one place.
Charlino
A: 

<%= Session["MyValue"] %> in the master page

Joe