Hello I would like to create my custom ActionFilterAttribute for each controller in my application, this attribute should set some ViewBag values. Is ActionFilterAttribute would be fine for it and how to get access to viewbag in ActionFilterAttribute ?
Asked
Active
Viewed 2.6k times
4 Answers
80
You can do like this
public class SomeMsgAttribute : FilterAttribute, IResultFilter
{
public void OnResultExecuted(ResultExecutedContext filterContext)
{
}
public void OnResultExecuting(ResultExecutingContext filterContext)
{
filterContext.Controller.ViewBag.Msg= "Hello";
}
}
Using:
[SomeMsg]
public ActionResult Index()
{
return View();
}
Ilya Sulimanov
- 7,636
- 6
- 47
- 68
-
Do you have any explanations about why this works in `Executing` but not in `Executed`? – Tolga Evcimen Mar 11 '16 at 07:54
-
4@TolgaEvcimen `OnResultExecuted` is invoked after the razor view is rendered. By that time, it is too late to change the output. – DPac Jun 22 '16 at 19:58
-
I see, I always thought it as `OnResultExecuted` invoked immediately after the action method returned, pity :) I should've thought it :) Thanks. – Tolga Evcimen Jun 23 '16 at 08:37
14
try this
public class CustomFilterAttribute : ActionFilterAttribute
{
public override void
OnActionExecuting(ActionExecutingContext filterContext)
{
// get the view bag
var viewBag = filterContext.Controller.ViewBag;
// set the viewbag values
viewBag.CustomValue = "CustomValue";
}
}
Anto Subash
- 3,140
- 2
- 22
- 30
6
For ASP.NET Core you can do the following
public class SomeFilterAttribute : IActionFilter
{
public void OnActionExecuting(ActionExecutingContext context)
{
Controller controller = context.Controller as Controller;
controller.ViewBag.CustomValue = customVal;
controller.ViewData["CustomValue "] = customVal;
controller.TempData["CustomValue "] = customVal;
}
}
Then from the controller
[TypeFilter(typeof(ValidateAppFeatureEnabled))]
public IActionResult Index()
{
var foo = ViewBag.CustomValue;
var bar = (type)ViewData["CustomValue"];
var buzz = (type)TempData["CustomValue"];
// Whatever else you need to do
return View();
}
Mkalafut
- 729
- 2
- 13
- 34
2
To transfer data from a different controller action
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
EmployeeTrackingSystemAndMISEntities db = new EmployeeTrackingSystemAndMISEntities();
var UserCookie = filterContext.HttpContext.Request.Cookies["UserUniqueID"];
RouteValueDictionary redirectTargetDictionary = new RouteValueDictionary();
redirectTargetDictionary.Add("action", "UserLogIn");
redirectTargetDictionary.Add("controller", "Login");
var TempData = filterContext.Controller.TempData;
TempData["Status"] = "Please log in as Admin";
filterContext.Result = new RedirectToRouteResult(redirectTargetDictionary);
}
Arun Prasad E S
- 9,489
- 8
- 74
- 87