Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Passing TempData from action filter to action

Tags:

asp.net-mvc

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 ?

like image 470
JAX Avatar asked Nov 06 '25 21:11

JAX


2 Answers

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();
}
like image 140
Kartikeya Khosla Avatar answered Nov 09 '25 06:11

Kartikeya Khosla


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


Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!