我可以从 ActionResult 检索 ViewModel 吗?

发布于 2024-10-12 02:39:04 字数 272 浏览 2 评论 0原文

在这里尽量避免重复。我在基类控制器中有一个不允许修改的操作。我希望我的操作执行一些检查,调用基类操作,并在渲染之前以某种方式修改结果。但我需要做的部分工作涉及修改 ViewModel 的一些属性,并且基类返回一个 ActionResult。我看不出有什么办法可以从 ActionResult 获取 ViewModel,因此我可能必须编写一个自定义方法,其中大多数方法只是模仿基类正在执行的操作。我强烈不想这样做。有什么建议吗?

Trying to avoid repetition here. I have an action in a base class controller which I am not allowed to modify. I'd like my action to do some checks, call the base class action, and modify the result in some way before rendering. But part of what I need to do involves modifying some properties of the ViewModel, and the base class returns an ActionResult. I see no way to get the ViewModel from the ActionResult, and so I may have to write a custom method, most of which would just mimic what the base class is doing. I'd strongly prefer not to do this. Any suggestions?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

郁金香雨 2024-10-19 02:39:04

这是因为 ActionResult 是一个相当高级的基类。尝试将其转换为适当的子类型,例如 ViewResult

快速示例代码:

    public ActionResult WrapperAction()
    {
        // do your initial stuff


        // call your base controller action and cast the result
        // it would be safer to test for various result types and handle accordingly
        ViewResult result = (ViewResult)base.SomeAction();

        object model = result.ViewData.Model;

        // do something with the model

        return result;
    }

That's because ActionResult is a fairly high-level base class. Try casting it to the appropriate subtype, such as ViewResult.

Quick sample code:

    public ActionResult WrapperAction()
    {
        // do your initial stuff


        // call your base controller action and cast the result
        // it would be safer to test for various result types and handle accordingly
        ViewResult result = (ViewResult)base.SomeAction();

        object model = result.ViewData.Model;

        // do something with the model

        return result;
    }
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文