Search code examples
asp.net-mvc-4viewbag

Extract the data from ViewBag at base ActionFilterAttribute


public class GeneralFilter : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)
    {
        dynamic val = filterContext.Controller.ViewBag;
        string action = filterContext.ActionDescriptor.ActionName;
        string controller = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
    }
}

In the above code, I am passing data from controller actions through viewbag. i am able to see those data at above mentioned variable val. how to extract the data from the variable dynamic val in the above code?!

when i browse with break point this is the flow

  • val {System.Web.Mvc.DynamicViewDataDictionary}
    • ViewData {System.Web.Mvc.ViewDataDictionary}
    • _innerDictionary Count = 1
      • [0] => My Required Data is here <= or
    • Values Count = 1
      • [0] => My Required Data is here <=

Solution

  • From my controller, if i pass data like this

    var Numbers = new List<int> { 1, 2, 3 };

    ViewBag.numbers = Numbers;

    then i can fetch the data from CustomfilterAttribute like this

    foreach (var number in filterContext.Controller.ViewBag.numbers)

    { var i = number; }

    Note: for this you need to assign the [GeneralFilter] only for methods which pass data of ViewBag.numbers else you have to face null reference error! i Appreciate for other better answers for this!?