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
Asked
Active
Viewed 420 times
2

Tassadaque
- 8,129
- 13
- 57
- 89
1 Answers
2
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.

Darin Dimitrov
- 1,023,142
- 271
- 3,287
- 2,928
-
I am getting null in filterContext.Result. I was thinking of second approach also let me see if it will do the trick – Tassadaque Feb 18 '12 at 11:50
-
@Tassadaque, what is null? `filterContext`? Or `filterContext.Result`? Or something else? How does your exact code look like? What about the controller action? – Darin Dimitrov Feb 18 '12 at 12:04
-
filterContext.Result is null in filtercontext i get ?filterContext {System.Web.Mvc.ActionExecutingContext} base {System.Web.Mvc.ControllerContext}: {System.Web.Mvc.ActionExecutingContext} ActionDescriptor: {System.Web.Mvc.ReflectedActionDescriptor} ActionParameters: Count = 7 Result: null – Tassadaque Feb 18 '12 at 12:14
-
I am just adding it in one of my customer actionfilterattribute's code which is public class RequiresAuthenticationAttribute : ActionFilterAttribute { public override void OnActionExecuting(ActionExecutingContext filterContext) – Tassadaque Feb 18 '12 at 12:16
-
@Tassadaque, of course that filterContext.Result will be null inside `OnActionExecuting`. This event is executed **before** the action runs so you cannot expect to have a result yet. You should use the `OnActionExecuted` event instead. – Darin Dimitrov Feb 18 '12 at 12:32
-
Oh thanks missed that. It is working now. but In my application renderaction is returning View() instead of PartialView(). So I think condition not get executed. Currently I have approach in which I use TempData with renderaction and using this at the moment but surely dig into it more. thanks – Tassadaque Feb 18 '12 at 12:46