I've been trying to pass TempData from ActionFilter to the action using :
filterContext.Controller.TempData.Add("Key","Value");
However, it appears that no TempData is passed to the action as I keep getting the Object not referenced to an instance of the object error.
Is this the right way to pass TempData to the controller from the ActionFilter ? if not, how can I do this ?
This will work :-
Answer 1 :
Filter :-
public class MyCustomAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RouteData.Values.Add("Key","Value");
}
}
Controller :-
[MyCustom]
public ActionResult Index()
{
TempData["Key"] = RouteData.Values["Key"];
return View();
}
Answer 2 :
Filter :-
public class MyCustomAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.TempData.Add("Key","Value");
}
}
Controller :-
[MyCustom]
public ViewResult Index()
{
string Tempval = TempData["Key"].ToString();
return View();
}
Filter code:
public class MyWhateverAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.TempData.Add("some key", "some value");
}
}
Action code:
[MyWhatever]
public ViewResult Index()
{
string value = TempData["some key"] as string;
return View();
}
Note: you must ensure that your filter code is executed before the action code in order to pass some value, that's why OnActionExecuting is the method that needs to be overridden
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With