Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get the Model from an ActionResult?

Tags:

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?

like image 743
Omu Avatar asked Jan 15 '10 11:01

Omu


1 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.

like image 135
Mark Seemann Avatar answered Oct 07 '22 00:10

Mark Seemann