user8280126
user8280126

Reputation:

MVC Core Get Controller ViewModel Results

I am trying to get result from Controller which calls Repository which extracts a ViewModel at the end, this is for Unit testing. The bold below is not working.

Compile error:

IAction Result does not contain a definition for View and no extension method View accepting a first argument of type IAction Result

public async Task<IActionResult> Search(int? id)
{
    return View(await _repository.GetProductData(id));
}

var searchresult1 = await _controller.Search(5);

var modelresult = searchresult1.View.ProductName;

Upvotes: 2

Views: 159

Answers (1)

jmesolomon
jmesolomon

Reputation: 563

try something like this

var searchresult1 = await _controller.Search(5) as ViewResult;
var result = searchResult.ViewName; // this should be the value returned from the controller

Or you can return the result as a ViewData.Model. So in your controller, you can probably do something like

return View("Product", await _repository.GetProductData(id)); 

Then in your test you can access the viewdata.model like

var result = await _controller.Search(5);
var productData = (ProductData) result.ViewData.Model; // cast it to whatever class the GetProductData(5) returns

Option 1 works at run time as the view name is set by the framework using route data. it is not available during unit testing. Which is why setting the view name manually in the second example works

Please see more details about MVC view model

Upvotes: 1

Related Questions