asp.net-mvc – 如何在使用类型化视图时在ActionFilterAttribute中设置模型数据

前端之家收集整理的这篇文章主要介绍了asp.net-mvc – 如何在使用类型化视图时在ActionFilterAttribute中设置模型数据前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我使用强类型视图,其中所有viewmodel都继承了一个类Baseviewmodel.

在装饰所有控制器的ActionFilter中,我想使用Model.

现在我只能像这样访问它:

public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        viewmodelBase model = (viewmodelBase)filterContext.ActionParameters["viewmodel"];
        base.OnActionExecuting(filterContext);
   }

问题是,我必须知道密钥“viewmodel”.关键是viewmodel,因为在我的控制器中我用过:

return
View(“MyView”,
viewmodel)

是否有更安全的方式来访问模型?

解决方法

OnActionExecuting在Action执行之前工作 – 因此Model被设置为null.您可以在OnActionExecuted中访问ViewData(或ViewData.Model):
public override void OnActionExecuted(ActionExecutedContext filterContext)
{
    var model = filterContext.Controller.ViewData.Model as YourModel;

    ...
}

希望这可以帮助

原文链接:https://www.f2er.com/aspnet/247815.html

猜你在找的asp.Net相关文章