Reputation: 1875
I'd like to get ViewBag
at OnResultExecuted
filter. Both
((ViewResultBase)filterContext.Result).ViewBag.Get
and
filterContext.Controller.ViewBag.Get
returns ViewBag
assigned at action. But I'd like to get ViewBag
assigned at "view.cshtml".
What I want to acheve is getting ViewBag
.Title from razor
@{
ViewBag.Title = "My Title";
}
And then, writing it to end of response text as a javascript. This is useful at @Ajax.ActionLink()
situations. My OnActionExecuted
filter code must be so:
string scriptText = "<script type='text/javascript'>document.title = '" + ViewBag.Title + "';</script>";
filterContext.HttpContext.Response.Write(scriptText);
Any help would be appreciated.
Upvotes: 1
Views: 1905
Reputation: 5666
You cannot pass values from view to controller. It is basically against the MVC pattern. When the view is executed it gets own copy of ViewData
(ViewBag
) so any changes to it are valid only in the scope of the view.
From Scott Guthrie's blog:
Views should not contain any application logic or database retrieval code, instead all application/data logic should only be handled by the controller class. The motivation behind this partitioning is to help enforce a clear separation of your application/data logic from your UI generation code. This makes it easier to unit test your application/data logic in isolation from your UI rendering logic.
Views should only render their output using the view-specific data passed to it by the Controller class. In the ASP.NET MVC Framework we call this view-specific data "ViewData". The rest of this blog post is going to cover some of the different approaches you can use to pass this "ViewData" from the Controller to the View to render.
Similar question with explanations is also here: Setting ViewData item in a Partial to be read in a View
So closer to your question. You cannot pass the value of Title to your action execution filter and you have to resolve it at the scope of the controller.
Upvotes: 1