Question

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?

Was it helpful?

Solution

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;
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top