How to set values to ViewBag in ActionFilterAttribute ASP MVC 5?
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);
}
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();
}
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";
}
}
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();
}