本文介绍了将TempData从动作过滤器传递到动作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我一直在尝试使用以下命令将TempData从ActionFilter传递到动作:
I've been trying to pass TempData from ActionFilter to the action using :
filterContext.Controller.TempData.Add("Key","Value");
但是,随着我不断收到Object not referenced to an instance of the object
错误,似乎没有将TempData传递给该动作.
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.
这是从ActionFilter传递TempData到控制器的正确方法吗?如果没有,我该怎么办?
Is this the right way to pass TempData to the controller from the ActionFilter ? if not, how can I do this ?
推荐答案
这将有效:-
答案1:
过滤器:-
public class MyCustomAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.RouteData.Values.Add("Key","Value");
}
}
控制器:-
[MyCustom]
public ActionResult Index()
{
TempData["Key"] = RouteData.Values["Key"];
return View();
}
答案2:
过滤器:-
public class MyCustomAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
filterContext.Controller.TempData.Add("Key","Value");
}
}
控制器:-
[MyCustom]
public ViewResult Index()
{
string Tempval = TempData["Key"].ToString();
return View();
}
这篇关于将TempData从动作过滤器传递到动作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!