Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen should an action be marked as async?
    primarykey
    data
    text
    <p>I have a controller action in mvc 4 app:</p> <pre><code>public ActionResult Index() { GetStartedModel gsModel = new GetStartedModel(); return View(gsModel); } </code></pre> <p>and ViewModel:</p> <pre><code>public class GetStartedModel { public IEnumerable&lt;SelectListItem&gt; listA { get; set; } public IEnumerable&lt;SelectListItem&gt; listB { get; set; } public GetStartedModel() { TestDataWebServiceHelper service = new TestDataWebServiceHelper(); this.GetData(service); } private async void SetData(TestDataWebServiceHelper service) { listA = await this.SetListA(service); listB = await this.SetListB(service); } private async Task&lt;IEnumerable&lt;SelectListItem&gt;&gt; SetListA(TestDataWebServiceHelper service) { List&lt;String&gt; rawList = new List&lt;String&gt;(); rawList = await service.GetValuesAsync("json"); return rawList.Select(x =&gt; new SelectListItem { Text = x, Value = x }); } private async Task&lt;IEnumerable&lt;SelectListItem&gt;&gt; SetListB(TestDataWebServiceHelper service) { List&lt;String&gt; rawList = new List&lt;String&gt;(); rawList = await service.GetValuesAsync("json"); return rawList.Select(x =&gt; new SelectListItem { Text = x, Value = x }); } } </code></pre> <p>When I call this controller action I receive following error:</p> <blockquote> <p>An asynchronous operation cannot be started at this time. Asynchronous operations may only be started within an asynchronous handler or module or during certain events in the Page lifecycle. If this exception occurred while executing a Page, ensure that the Page is marked &lt;%@ Page Async="true" %>.</p> </blockquote> <p>So, questions:</p> <ol> <li>Should I somehow mark controller or action or page itself as asynchronous to allow this model initialization?</li> <li>Is it possible to encapsulate all initialization logic to viewmodel and not to pop it to the controller?</li> <li>What is the reason of that error? Seem like it related to WebForms, but I use Razor engine.</li> </ol>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload