How do I pass a variable from an ActionFilter to a Controller Action in C# MVC?
I believe ActionExecutingContext
contains a reference to the calling controller. Using this mixed with a custom controller class derived from the base Controller
class to then store the id
as an instance variable of the controller would probably do it.
Custom controller
Public Class MyController : Controller
{
Public int Id {get;set;}
}
LoginFilter
public class LoginFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Authenticate (somehow) and retrieve the ID
int id = Authentication.SomeMethod();
((MyController)filterContext.Controller).Id = id;
//Assign the Id by casting the controller (you might want to add a if ... is MyController before casting)
}
}
Controller
[LoginFilter]
public class Dashboard : MyController
{
public ActionResult Index()
{
//Read the Id here
int id = this.Id
}
}
You can use ViewData/ViewBag
like this:
1.) Using ViewData
NOTE: In case of ViewData you need to do one step that is you have to typecast it
public class LoginFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Authenticate (somehow) and retrieve the ID
int idValue = Authentication.SomeMethod();
// Pass the ID through to the controller?
filterContext.Controller.ViewData.Add("Id", idValue);
}
}
And then in Controller function
[LoginFilter]
public class Dashboard : Controller
{
public ActionResult Index()
{
// I'd like to be able to use the ID from the LoginFilter here
int id = (int)ViewData["Id"];
}
}
2.) Using ViewBag
public class LoginFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
// Authenticate (somehow) and retrieve the ID
int idValue = Authentication.SomeMethod();
// Pass the ID through to the controller?
filterContext.Controller.ViewBag.Id = idValue;
}
}
And then in controller
[LoginFilter]
public class Dashboard : Controller
{
public ActionResult Index()
{
// I'd like to be able to use the ID from the LoginFilter here
int id = ViewBag.Id;
}
}
You can use the ViewBag
by doing:
filterContext.Controller.ViewBag.Id = id;
that should do it, once you do filterContext.Controller
you have access to all fields inside it like TempData
as well.
Even so, if you are using OWIN
then perhaps to get a user's id you could use the Controller.User
which has an extension method to get the Id
and properties to get most other standard data like Name
etc.