Tassadaque
Tassadaque

Reputation: 8199

Fill ViewData on Every Action but not on renderaction

I have a viewData that is required to be available on each page. If I fill this ViewData using onActionExecuting. It gets filled for every action even for actionresult of partial pages. I want ViewData to be get filled only once for each Page Load. Any suggestion

Upvotes: 2

Views: 423

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038940

You could use the OnActionExecuting event and test if the result returned b the view is a normal view or a partial view and based on that decide whether or not to add the information to ViewData:

public class MyActionFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        if (filterContext.Result is ViewResult)
        {
            filterContext.Controller.ViewData["foo"] = "bar";
        }
    }
}

Another possibility to have some common data available to all views is to externalize it in a separate child action and use the Html.Action helper to include it in your layout for example.

Upvotes: 2

Related Questions