How to get the Model from an ActionResult?

Viewed 36484

I'm writing a unit test and I call an action method like this

var result = controller.Action(123);

result is ActionResult and I need to get the model somehow, anybody knows how to do this?

4 Answers

In my version of ASP.NET MVC there is no Action method on Controller. However, if you meant the View method, here's how you can unit test that the result contains the correct model.

First of all, if you only return ViewResult from a particular Action, declare the method as returning ViewResult instead of ActionResult.

As an example, consider this Index action

public ViewResult Index()
{
    return this.View(this.userViewModelService.GetUsers());
}

you can get to the model as easily as this

var result = sut.Index().ViewData.Model;

If your method signature's return type is ActionResult instead of ViewResult, you will need to cast it to ViewResult first.

consider a = ActionResult;

ViewResult p = (ViewResult)a;
p.ViewData.Model
Related