Water Cooler v2
Water Cooler v2

Reputation: 33850

Data I pass from ActionFilter via ViewBag not accessible in View

I want to pass some information from a custom action filter to a view. I use the ViewBag like so but in the view, both the properties ViewBag.Title and ViewBag.Message evaluate to 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" 
            };
}

In the View

<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>

Upvotes: 4

Views: 2378

Answers (1)

Shyju
Shyju

Reputation: 218732

There is a ViewBag property on the ViewResult where you can set the viewBag items you want to pass to the view. You can set a dynamic object as the value.

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

Upvotes: 6

Related Questions