I want to get ViewData value from httpcontext. My function:
[LogActionFilter]
public ActionResult Edit(int id = 0)
{
var obj = getObjFromDb(id);
ViewData["abc"] = obj.name;
return View(obj);
}
My action filter where I want to to access ViewData
value:
public class LogActionFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var a= filterContext.HttpContext.Items["abc"]; //null
var b = filterContext.HttpContext.Request.RequestContext.HttpContext.Items["abc"]; //null
}
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var a= filterContext.HttpContext.Items["abc"]; //null
var b = filterContext.HttpContext.Request.RequestContext.HttpContext.Items["abc"]; //null
}
}
How can I access the value of ViewData
from HttpContext
?
You can use session to pass value into your OnActionExecuted filter. However you can't pass anything from your action to OnActionExecution because its executed before your action.
[LogActionFilter]
public ActionResult Edit(int id = 0)
{
var obj = getObjFromDb(id);
Session["abc"] = obj.name;
return View(obj);
}
In filter:
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
var a = filterContext.HttpContext.Session["abc"];
/// a should have a value
}
Thanks to Stephen Muecke,
ViewData
is not available inHttpContext
So I changed my logic, instead of getting viewdata
value, I fetched data from database in action filter.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.