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;

    ...
}

希望这可以帮助

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....