简体   繁体   中英

Can I update my model or other classes from inside an actionfilter

I have the following actionfilter:

public class PopulateMetaAttribute : ActionFilterAttribute
{
    public override void OnActionExecuted(ActionExecutedContext filterContext)   
    {
        var a = filterContext.Controller.ViewData.Model. ???
        return;
    }
}

I would like to update my model or a class that is defined in the action that just caused the action filter to run. What I tried to do was code the line starting with var a. All worked okay until I got to the word Model and then intellisense didn't give me any suggestion on fields.

Am I going about this the right way. I thought if I choose the OnActionExecuted then the fields in my method would be available.

Can someone explain if I can access this model data or if I can update fields in classes in my action method.

You can, but you will need to cast it. For example:

var a = filterContext.Controller.ViewData.Model as MyViewModel;
if (a != null)
{
    a.MyProperty = ...;
}

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM