Use of await in Razor views

前端 未结 8 883
面向向阳花
面向向阳花 2020-11-28 12:48

Is it possible to await on tasks in Razor .cshtml views?

By default it complains that it can only be used in methods marked with async so I

8条回答
  •  感情败类
    2020-11-28 13:01

    I know this is an older thread, but I'll add my input just in case someone else finds it useful. I ran into this problem working with the new MongoDB driver in ASP.Net MVC - the new driver (for now), only implements async methods and returns async cursors, which can't be used in a foreach because asynccursor doesn't implement IEnumerable. The sample code typically looks like:

    while(await cursor.movenextasync)
        var batch=cursor.current
        foreach(var item in batch)
            --do stuff here--
    

    But, this doesn't work in razor, because views are inherently not async, and await doesn't cut it.

    I got it to work by changing the first line to:

    while(cursor.MoveNextAsync().Result)
    

    which returns true until the cursor hits the last entry.

    Hope that helps!

提交回复
热议问题