【问题标题】:Extract the data from ViewBag at base ActionFilterAttribute从基本 ActionFilterAttribute 的 ViewBag 中提取数据
【发布时间】:2019-04-06 21:05:16
【问题描述】:
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;
    }
}

在上面的代码中,我通过 viewbag 传递来自控制器动作的数据。我能够在上述变量 val 处看到这些数据。如何从上述代码中的变量dynamic val中提取数据?!

当我用断点浏览时,这就是流程

  • val {System.Web.Mvc.DynamicViewDataDictionary}
    • ViewData {System.Web.Mvc.ViewDataDictionary}
    • _innerDictionary 计数 = 1
      • [0] => 我需要的数据在这里
    • 值计数 = 1
      • [0] => 我需要的数据在这里

【问题讨论】:

    标签: asp.net-mvc-4 viewbag


    【解决方案1】:

    从我的控制器,如果我像这样传递数据

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

    ViewBag.numbers = Numbers;

    然后我可以像这样从 CustomfilterAttribute 中获取数据

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

    { var i = number; }

    注意:为此,您只需为传递 ViewBag.numbers 数据的方法分配 [GeneralFilter],否则您将面临空引用错误! 我感谢其他更好的答案!?

    【讨论】:

    • 为了避免空引用错误,只需放置一个像这样的 if 条件 "if(filterContext.Controller.ViewBag.numbers !=null)" 它对我有用!有更好的答案吗?
    猜你喜欢
    • 2020-05-07
    • 1970-01-01
    • 2012-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-08-16
    • 2022-01-14
    • 1970-01-01
    相关资源
    最近更新 更多