Can I get a ViewModel from an ActionResult?

Try to avoid repetition here. I have an action in the base class controller that I am not allowed to modify. I would like my action to perform some checks, invoke the action of the base class, and somehow modify the result before rendering. But part of what I need to do involves modifying some properties ViewModel, and the base class returns ActionResult. I don’t see a way to get ViewModelfrom ActionResult, so I may have to write my own method, most of which simply imitate what the base class does. I would rather not do this. Any suggestions?

+3
source share
1 answer

This is because it ActionResultis a fairly high-level base class. Try applying it to the appropriate subtype, for example ViewResult.

Quick code example:

    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;
    }
+8
source

Source: https://habr.com/ru/post/1785546/


All Articles