我通过ViewBag从ActionFilter传递的数据无法在View中访问

时间:2015-12-03 10:38:54

标签: asp.net-mvc asp.net-mvc-5

我想将自定义操作过滤器中的一些信息传递给视图。我像这样使用ViewBag,但在视图中,属性ViewBag.TitleViewBag.Message都评估为null

public override void OnActionExecuting(ActionExecutingContext filterContext)
{
    ...

    filterContext.Controller.ViewBag.Title = "Session Expired";
    filterContext.Controller.ViewBag.Message = "Your session has expired. Please login again.";
    filterContext.Result = 
            new ViewResult 
            { 
              ViewName = "~/Views/Shared/Info.cshtml" 
            };
}

在视图中

<div class="row">
        <div class = 
             "col-lg-8 col-md-8 col-sm-8 col-xs-12 
              col-lg-offset-2 col-md-offset-2 col-sm-offset-2 
              col-xs-offset-0">

            <h2>@ViewBag.Title</h2>

            <h3>@ViewBag.Message</h3>
        </div>
</div>

1 个答案:

答案 0 :(得分:5)

ViewResult上有一个ViewBag属性,您可以在其中设置要传递给视图的viewBag项。您可以将动态对象设置为值。

filterContext.Result = new ViewResult
                          {
                             ViewName = "~/Views/Shared/Info.cshtml" ,
                             ViewBag= { Message="SS",Title="Hi title"}
                          };