1

My model has an async method which I would like to invoke from within a view, i.e. something like this:

@Ajax.ActionLink(await Model.GetCaptionAsync(), ...

The VS 2015 IDE however complains that await can only be used from within an async method.

Is there a reasonable way to invoke an async mehthod from within a view (i.e. not using .Result but keeping the async flow)?

Henrik Dahl
  • 121
  • 1
  • 1
  • 7
  • 2
    For my project I created a regular backend method that itself called an async method, which called the asynchronous function with await. Will that work for you? – VictorySaber Mar 30 '16 at 08:01
  • Create an Action ( and call it via **ajax** ) and call the desired async method through it – Asif Mehmood Mar 30 '16 at 08:03
  • Actual work should be performed by the *Controller*, not the view model. Why wait until rendering to retrieve a value when that could be done in the controller? That suggests either a) a controller masquerading as a model and/or b) a model that contains more properties that are *actually* needed for the view, making lazy loading necessary – Panagiotis Kanavos Mar 30 '16 at 09:04

1 Answers1

-1

you shouldn't see: Use of await in Razor views

refer to: http://www.asp.net/mvc/overview/performance/using-asynchronous-methods-in-aspnet-mvc-4

just call it with .Wait()

Community
  • 1
  • 1
Nahum
  • 6,959
  • 12
  • 48
  • 69
  • 2
    Can't your recommendation on invoking .Wait() lead to a deadlock in the same way as if it were in a Windows Forms or WPF application (because you force some other process on top of the automatic scheduling)? – Henrik Dahl Mar 30 '16 at 09:05
  • @HenrikDahl first no, why would it? There's no UI thread in web applications and second - view models are DTOs, it's the *controllers' actions* that should be doing the async work. Even if you use `.Result` or `.Wait()` there's something wrong with a model that wants to actually do stuff asynchronously – Panagiotis Kanavos Mar 30 '16 at 09:07
  • 3
    It doesn't matter that there is no UI thread. It matters if there is a SynchronizationContext in use which can be deadlocked. Shouldn't we rather skip these lesson one comments on trivialities like DTOs and async work should be done in the controller. My view needs some further data for the purpose of producing its result and it should not be cluttered into the model where it has nothing to do from the conceptual purpose of a model. In fact it is a specific DisplayTemplate which has the need and not the federating view. – Henrik Dahl Mar 30 '16 at 09:32
  • Don't use this answer and task.Wait(), it leads you to deadlocks – JaktensTid Mar 24 '21 at 14:32