Search code examples
c#asynchronousrazorasync-awaitasp.net-mvc-5

How to call an asynchronous method from a view?


I have an async method in a controller that has an id parameter. In my view, I want to have a button that when clicked it passes a @document.SubmissionId variable to the function and execute it. How can I achieve that? Here is what I have so far:

Controller

private async Task<ActionResult> onPostSaveImage(string id){}

View

<input type="button" value="Send Images" class="btn btn-xs btn-outline-primary" onclick="location.href='@Url.Action("onPostSaveImage", "ICRDocumentPending")?id=' + @document.SubmissionId" />

Solution

  • Not enough just sign a method with async to be able work asynchronously when called from a view. It is necessary to derive your controller class from System.Web.Mvc.AsyncController, which implements IAsyncController interface. And code will become like below:

    public class ICRDocumentPendingController : AsyncController
    {
        public async Task<ActionResult> onPostSaveImage(string id)
        {           
            return await Task<ActionResult>.Factory.StartNew(() =>
            {
                /*  some code */
                //...
    
                return View("ViewName", (object)id); 
             });
         }
         //...
    }
    

    View code:

    <input type="button" value="Send Images" 
           class="btn btn-xs btn-outline-primary"
           onclick="location.href='@Url.Action("onPostSaveImage", "ICRDocumentPending", new { id = document.SubmissionId }))'" />