Mihaly
Mihaly

Reputation: 301

Solving CS0029 when returning a viewresult after async task

I get a CS0029 error when I try to return a view using the data that have been recieved from MongoDb.

[HttpGet("{id}")]
public async Task<RecommendationModel> Get(string id)
{
    return View ("RecommendationDetails", await _recommendationRepository.GetRecommendation(id));
}

When I just return the await (see below), I get a correct JSON result.

[HttpGet("{id}")]
public async Task<RecommendationModel> Get(string id)
{
    return await _recommendationRepository.GetRecommendation(id));
}

Can anybody point me in the right direction?

Upvotes: 0

Views: 298

Answers (1)

poke
poke

Reputation: 387707

Returning View() from a controller action returns a ViewResult which is an IActionResult. So you should have your method return a Task<IActionResult>:

public async Task<IActionResult> Get(string id)
{
    var model = await _recommendationRepository.GetRecommendation(id);
    return View("RecommendationDetails", model);
}

This is different from returning a model directly which causes the MVC framework to return your model directly as a JSON. But here, you want to actually invoke your Razor view and you just pass the model to the view for it to be rendered in some way.

Upvotes: 2

Related Questions